我正在尝试获取HTTP标头,但只获取服务器软件示例:Apache、Microsoft iis、Nginx等
功能
get_headers($url,1);
它太慢了,我想确定时间,如果可能的话还是其他方式??
感谢
对于本地服务器,$_server变量将提供web服务器在server_*密钥中公开的所有内容。
对于远程服务器,您可以使用libcurl并只请求标头。然后解析响应。根据网络连接和其他服务器的速度,它仍然可能有很长的延迟。为了避免长延迟,例如对于离线服务器,请使用curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5)
将curl选项设置为短超时(例如5秒)。
这会将代码设置为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:"标头。
您可以使用cURL来实现这一点,它将允许您从远程服务器获取响应。您也可以使用cURL设置超时。
通过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.1rn");
fputs($fp,"Host:$url[host]rnrn");
$ret = '';
while (!feof($fp)) {
$tmp = fgets($fp);
if(trim($tmp) == '') {
break;
}
$ret .= $tmp;
}
preg_match('/[rn]Server:s([a-zA-Z]*)/is',$ret,$match);
return $match[1];
//return $ret;
} else {
return null;
}
}
$servername= getHttpHead('http://google.com');
echo $servername;