php实现获取网页请求状态非get_headers

作者:enenba | 发表于:2012-12-04 08:38 | 分类:php源码
function get_http_code($url="localhost", $port=80, $fsock_timeout=10){ 
    set_time_limit(0); 
    ignore_user_abort(true); 
  
    // 记录开始时间 
    list($usec, $sec) = explode(" ", microtime(true)); 
    $timer['start'] = (float)$usec + (float)$sec; 
  
    // 校验URL 
    if(!preg_match("/^https?:\/\//i", $url)){ 
        $url = "http://".$url; 
    } 
    // 支持HTTPS 
    if(preg_match("/^https:\/\//i", $url)){ 
        $port = 443; 
    } 
  
    // 解析URL 
    $urlinfo = parse_url($url); 
    if(empty($urlinfo['path'])){ 
        $urlinfo['path'] = '/'; 
    } 
    $host = $urlinfo['host']; 
    $uri = $urlinfo['path'] . (empty($urlinfo['query'])?'':$urlinfo['query']); 
  
    // 通过fsock打开连接 
    if(!$fp = fsockopen($host, $port, $errno, $error, $fsock_timeout)){ 
        list($usec, $sec) = explode(" ", microtime(true)); 
        $timer['end'] = (float)$usec + (float)$sec; 
        $usetime = (float)$timer['end'] - (float)$timer['start']; 
  
        return array('code'=>-1, 'usetime'=>$usetime); 
    } 
  
    // 提交请求 
    $status = socket_get_status($fp); 
    $out = "GET {$uri} HTTP/1.1\r\n"; 
    $out .= "Host: {$host}\r\n"; 
    $out .= "Connection: Close\r\n\r\n"; 
    $write = fwrite($fp, $out); 
    if(!$write){ 
        list($usec, $sec) = explode(" ", microtime(true)); 
        $timer['end'] = (float)$usec + (float)$sec; 
        $usetime = (float)$timer['end'] - (float)$timer['start']; 
  
        return array('code'=>-2, 'usetime'=>$usetime); 
    } 
  
    $ret = fgets($fp, 1024); 
    preg_match("/http\/\d\.\d\s(\d+)/i", $ret, $m); 
    $code = $m[1]; 
    fclose($fp); 
  
    list($usec, $sec) = explode(" ", microtime(true)); 
    $timer['end'] = (float)$usec + (float)$sec; 
    $usetime = (float)$timer['end'] - (float)$timer['start']; 
  
    return array('code'=>$code, 'usetime'=>$usetime); 
}
原文地址:http://blog.qita.in/?post=707

 

 

 

上一篇: php模板引擎常见的变量解析语法   |   下一篇:使用curl获取Location:重定向后url» 标签: php获取 headers http状态

评论:

2012-12-24 11:16

这个页面请求喜欢

2012-12-08 20:18

这算是底层实现吗?效率和get_headers比起来怎么样?

2012-12-09 00:03

明显不是底层。效率没测试,不敢妄下结论。

2012-12-07 10:00

代码弄起来需要时间那,厉害。