我想解析很多 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
。如果只需要响应标头,可以使用 HTTP 方法HEAD
。
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'HEAD');
根据@Dai的回答,NOBODY 已经在使用 HEAD 方法。所以上面的方法行不通。
另一种选择是使用 fsockopen
打开连接,使用 fwrite
写入标头。使用 fgets
读取响应,直到第一次出现 'r'n'r'n
以获取完整的标头。由于您只需要状态代码,因此您只需要读取前 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);
}
cURL 的nobody
选项使用它使用 HTTP 动词HEAD
,我敢打赌大多数非静态 Web 应用程序我野生没有正确处理这个动词,因此你看到的问题有不同的结果。我建议发出正常的GET
请求并丢弃响应。
我建议改get_headers()
:
<?php
$url = 'http://www.example.com';
print_r(get_headers($url));
print_r(get_headers($url, 1));
?>