啥也不说了。直接上代码了。主要是用来检查路径文件是否存在:
PHP代码
- class Headers
- {
- static private $headers;
- static private $getmodes = array('fsock','curl');
- static private $getmode;
- static private $type;
- public static function init ($type = 'status'){
- self::$type = strToLower( $type );
- }
- public static function get ( $url ,$mode='')
- {
- list( $host, $uri , $url ) = self::initURL($url);
- if($mode && in_array( strToLower( $mode ), self::$getmodes )){
- self::$getmode = $mode;
- }
- return self::_get( $host , $uri ,$url);
- }
- private static function initURL ( $url )
- {
- $urls = parse_url( $url );
- return array($urls['host'],$urls['path'],$url);
- }
- private static function _get ( $host , $uri,$url )
- {
- if(self::$getmode == 'curl' && function_exists( 'curl_init' )){
- return self::_curlopen($host,$uri,$url);
- }else{
- return self::_fsockopen($host,$uri);
- }
- }
- private static function _curlopen ($host,$uri,$url){
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url );
- curl_setopt($ch, CURLOPT_HEADER, 1);
- curl_setopt($ch, CURLOPT_HTTPGET, 1);
- curl_setopt($ch,CURLOPT_NOBODY,1);
- curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
- curl_setopt($ch, CURLOPT_TIMEOUT, 60);
- $result = curl_exec($ch);
- // echo '<pre>';
- // print_r( curl_getinfo($ch) );
- // echo '</pre>';
- curl_close($ch);
- if(self::$type == 'status'){
- return subStr( $result, 0 , strPos( $result, "" ) );
- }
- return array_filter(explode( "", $result ));
- }
- private static function _fsockopen ($host,$uri)
- {
- $headers = array();
- $header=$errno=$errstr='';
- $fp = fsockopen ($host, 80, $errno, $errstr, 60);
- if ($fp){
- fputs ($fp, "GET $uri HTTP/1.0");
- if(self::$type == 'status' ){
- $get=fgetss( $fp );
- return trim( $get );
- }else{
- while (!feof($fp)){
- $char = fgetc($fp);
- if($char === "\n"){
- if (ord($header) === 13){
- return $headers;
- }else{
- array_push($headers, trim($header));
- }
- $header = '';
- }else{
- $header = $header.$char;
- }
- }
- }
- fclose ($fp);
- }
- }
- }
- $s = microtime(1);
- $get = Headers::get('http://www.neatstudio.com/testtt.php','curl');
- echo '<pre>';
- print_r( $get );
- echo '</pre>';
- echo( sprintf( "%0.6f" , (microtime(1)-$s) ) );
curl函数中我有一段是注释掉的。如果只是为了取状态,直接运行完后curl_getinfo就OK了。然后取其中的http_code,就可以知道当前的状态。
当然。http_code的具体对应可以参考常用http code
【后记】看到BOPO的回复,才发现。。。郁闷,原来get_headers就可以了。我居然忘了这个函数。傻掉了我。唉。。。。不过这也是从PHP5才开始有的函数。看来我对手册的了解度下降了