如何获取服务器软件的http标头并设置超时

时间:2012-07-20 15:14:17

标签: php http-headers

我正在尝试获取HTTP标头,但只是服务器软件示例:Apache,Microsoft-iis,Nginx等

功能

get_headers($url,1); 

它太慢了我想设置超时,如果有可能或其他方式?

感谢

4 个答案:

答案 0 :(得分:1)

对于本地服务器,$_SERVER变量将为您提供SERVER_ *密钥中Web服务器公开的所有内容。

对于远程服务器,您可以使用libcurl并仅请求标头。然后解析响应。它仍然可能是长延迟,具体取决于网络连接和其他服务器的速度。为了避免长时间的延迟,例如对于脱机服务器,使用curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5)将curl选项设置为短暂超时(例如5秒)。

答案 1 :(得分:1)

这会将代码设置为2秒后超时,如果需要毫秒,可以使用CURLOPT_TIMEOUT_MS。

$timeoutSecs = 2;

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, true); // Return the header
curl_setopt($ch, CURLOPT_NOBODY, true); // Don't return the body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return to a variable instead of echoing
curl_setopt($ch, CURLOPT_TIMEOUT, $timeoutSecs);

$header = curl_exec($ch);
curl_close($ch);

编辑:请注意,您不仅可以从中获取单个标题,它将返回整个标题(这不会比仅仅获得一个片段慢),因此您需要创建拉出“Server:”标题的模式。

答案 2 :(得分:0)

您可以使用cURL执行此操作,这将允许您从远程服务器获取响应。您也可以使用cURL设置超时。

答案 3 :(得分:0)

通过curl或fsockopen获取标题,解析它你想要的。

fsockopen的函数是超时的最后一个参数。

curl的函数调用“curl_setopt($ curl,CURLOPT_TIMEOUT,5)”表示超时。

例如:

function getHttpHead($url) {
$url = parse_url($url);
if($fp = @fsockopen($url['host'],empty($url['port']) ? 80 : $url['port'],$error,
    $errstr,2)) {
    fputs($fp,"GET " . (empty($url['path']) ? '/' : $url['path']) . " HTTP/1.1\r\n");
    fputs($fp,"Host:$url[host]\r\n\r\n");
    $ret = '';
    while (!feof($fp)) {
        $tmp = fgets($fp);
        if(trim($tmp) == '') {
            break;
        }
        $ret .= $tmp;
    }
    preg_match('/[\r\n]Server\:\s([a-zA-Z]*)/is',$ret,$match);
    return $match[1];
    //return $ret;
} else {
    return null;
}
}
$servername= getHttpHead('http://google.com');

echo $servername;