PHP get_headers()替代方案

时间:2011-05-22 10:00:41

标签: php http-headers httpresponse

我需要一个PHP脚本来读取每个URL请求的HTTP响应代码。

类似

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

问题是在服务器级别禁用了get_headers()函数作为策略。因此它不起作用。

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

3 个答案:

答案 0 :(得分:11)

如果启用了cURL,您可以使用它来获取整个标头或仅获取响应代码。以下代码将响应代码分配给$response_code变量:

$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请求,如下所示:

$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 );

答案 1 :(得分:4)

如果可以,请使用HttpRequest:http://de2.php.net/manual/en/class.httprequest.php

$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]);

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

答案 2 :(得分:3)

您可以使用fsockopen和常规文件操作构建和读取自己的HTTP查询。看看我之前关于这个主题的答案:

Are there any other options for rest clients besides CURL?