我想解析很多 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/