php获取网页请求状态示例分享

发布时间:2020-03-10编辑:脚本学堂
分享一例php获取网页请求状态的代码,有需要的朋友参考下。

例子,获取网页请求状态。
 

复制代码 代码示例:
<?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.1rn";
    $out .= "Host: {$host}rn";
    $out .= "Connection: Closernrn";
    $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);
    } // www.jb200.com
 
    $ret = fgets($fp, 1024);
    preg_match("/http/d.ds(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);
}