2011-05-22 69 views
5

我需要一个PHP脚本来读取每个URL请求的HTTP响应代码。PHP get_headers()替代方案

$headers = get_headers($theURL); 
return substr($headers[0], 9, 3); 

的问题是get_headers()函数在服务器级被禁止,作为policy.So这是行不通的。

问题是如何获取URL的HTTP响应代码?

回答

10

如果卷曲启用,您可以使用它来获取整个头部或只是响应代码。下面的代码响应代码分配给$response_code变量:如果你能

$curl = curl_init(); 
curl_setopt_array($curl, array(
    CURLOPT_HEADER => true, 
    CURLOPT_NOBODY => true, 
    CURLOPT_RETURNTRANSFER => true, 
    CURLOPT_URL => 'http://stackoverflow.com')); 
$headers = explode("\n", curl_exec($curl)); 
curl_close($curl); 
+0

谢谢大家!启用CURL做到了这一点! – 2011-05-22 11:21:13

+0

@Matej是的,它运行良好,但是有一个简单的说明,我认为我们不会像“Apache或iis等等”那样获得他们使用的“服务器”等一些细节。但要检查服务器响应代码,它工作正常。 – VKGS 2011-10-06 06:26:17

+0

@Sekar:“服务器”是可选的,它依赖于服务器是否发送。 – 2011-10-06 19:19:20

4

使用的HttpRequest:http://de2.php.net/manual/en/class.httprequest.php

$curl = curl_init(); 
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => true, 
    CURLOPT_URL => 'http://stackoverflow.com')); 
curl_exec($curl); 
$response_code = curl_getinfo($curl, CURLINFO_HTTP_CODE); 
curl_close($curl); 

为了让整个头,你可以发出一个HEAD请求,这样

$request = new HttpRequest("http://www.example.com/"); 
$request->send(); 
echo $request->getResponseCode(); 

或者做硬盘的方式:http://de2.php.net/manual/en/function.fsockopen.php

$errno = 0; 
$errstr = ""; 

$res = fsockopen('www.example.com', 80, $errno, $errstr); 

$request = "GET/HTTP/1.1\r\n"; 
$request .= "Host: www.example.com\r\n"; 
$request .= "Connection: Close\r\n\r\n"; 

fwrite($res, $request); 

$head = ""; 

while(!feof($res)) { 
    $head .= fgets($res); 
} 

$firstLine = reset(explode("\n", $head)); 
$matches = array(); 
preg_match("/[0-9]{3}/", $firstLine, $matches); 
var_dump($matches[0]); 

卷曲可能也是一个不错的选择,但最好的选择是打败你的管理员;)