php - 使用 cURL 获取没有正文的 http-statuscode?

标签 php performance curl http-status-codes

我想解析很多 URL,只获取它们的状态代码。

所以我所做的是:

$handle = curl_init($url -> loc);
             curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
             curl_setopt($handle, CURLOPT_HEADER  , true);  // we want headers
             curl_setopt($handle, CURLOPT_NOBODY  , true);
             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
             $response = curl_exec($handle);
             $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
             curl_close($handle);

但是,一旦“nobody”选项设置为 true,返回的状态代码就会不正确(google.com 返回 302,其他网站返回 303)。

由于性能损失,无法将此选项设置为 false。

有什么想法吗?

最佳答案

curl 的默认 HTTP 请求方法是 GET。如果您只需要响应 header ,可以使用 HTTP 方法 HEAD

curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'HEAD');

根据@Dai的回答,NOBODY已经在使用HEAD方法了。所以上面的方法不行。

另一种选择是使用 fsockopen 打开连接,使用 fwrite 写入 header 。使用 fgets 读取响应,直到第一次出现 \r\n\r\n 以获取完整的 header 。由于您只需要状态代码,因此只需读取前 13 个字符。

<?php
$fp = fsockopen("www.google.com", 80, $errno, $errstr, 30);
if ($fp) {
    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host: www.google.com\r\n";
    $out .= "Accept-Encoding: gzip, deflate, sdch\r\n";
    $out .= "Accept-Language: en-GB,en-US;q=0.8,en;q=0.6\r\n";
    $out .= "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36\r\n";
    $out .= "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    $tmp = explode(' ', fgets($fp, 13));
    echo $tmp[1];
    fclose($fp);
}

关于php - 使用 cURL 获取没有正文的 http-statuscode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27236135/

相关文章:

php - 如何在php脚本中转义这个mysql查询?

c# - 如何在 C#.net 中使用 Linq 表达式或 AsEnumerable 转换 Foreach 循环?

php - mysql更新,性能WHERE检查与不检查

php - 如何从远程服务器自动提交(POST)表单?

php - curl 函数在 php5.6 中不起作用

php - 重复 JavaScript AJAX 请求,直到状态发生变化

php - Laravel 5 唯一验证不起作用

PHP 表单不发送任何 $_POST 值

performance - 如何通过id快速查找sharepoint文档库?

curl - 如何列出替代证书主题名称