我正在浏览用户提供的 URL 列表,以查看哪些 URL 在请求时没有从服务器获得有效的 HTTP 响应代码。在 QA 期间,我们发现看起来像http://broken
的链接没有被标记为无效。
我们有一个 php 脚本,它使用 cURL 来获取 http 标头并解析出响应代码。如果有多个重定向,我们确实允许重定向并使用返回的最终响应代码来跟踪它们。一项测试是说请求http://broken
返回 200。显然不是我想要的。我认为,格式不正确的 url 应该会生成 404 响应。
我将代码提取到一个小型测试工具中:
<?php
util_url_get_response_code("http://broken", true);
function util_url_get_response_code ($url, $follow_redirect = false) {
$handle = curl_init($url);
curl_setopt( $handle, CURLOPT_NOBODY, true );
curl_setopt( $handle, CURLOPT_HEADER, true );
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE);
if ($follow_redirect) { curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true); }
$data = curl_exec( $handle );
$err = curl_error($handle);
curl_close( $handle );
print_r($data);
}
?>
运行该测试代码时,打印的标题如下所示:
HTTP/1.1 302 Found
Date: Mon, 10 Jun 2013 17:39:30 GMT
Server: Apache/2.0.52 (CentOS)
X-Powered-By: PHP/5.1.6
Location: http://www.nitrc.org/
Content-Type: text/html; charset=UTF-8
HTTP/1.1 200 OK
Date: Mon, 10 Jun 2013 17:39:40 GMT
Server: Apache/2.0.52 (CentOS)
X-Powered-By: PHP/5.1.6
Set-Cookie: PHPSESSID=oorncckdt198341u4lccpoai12; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Type: text/html; charset=UTF-8
查看第一个标头,cURL 似乎联系了 www.nitrc.org 服务器……这是我们的网站 URL。NITRC 被配置为将未知 URL 重定向到主页,因此我们最终会得到 200 OK 响应标头。
那么,我该怎么做才能让 cURLhttp://broken
像浏览器一样查看并返回 404 错误?
(请注意,我无法关闭重定向处理,因为它是遵循任何有效重定向的要求的一部分!)