我为网页的 HTTP 代码创建了以下 PHP 函数。
function get_link_status($url, $timeout = 10)
{
$ch = curl_init();
// set cURL options
$opts = array(CURLOPT_RETURNTRANSFER => true, // do not output to browser
CURLOPT_URL => $url, // set URL
CURLOPT_NOBODY => true, // do a HEAD request only
CURLOPT_TIMEOUT => $timeout); // set timeout
curl_setopt_array($ch, $opts);
curl_exec($ch); // do it!
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE); // find HTTP status
curl_close($ch); // close handle
return $status;
}
如何修改此函数以遵循 301 和 302 重定向(可能多次重定向)并获取最终的 HTTP 状态代码?
最佳答案
将 CURLOPT_FOLLOWLOCATION
设置为 TRUE
。
$opts = array(CURLOPT_RETURNTRANSFER => true, // do not output to browser
CURLOPT_URL => $url, // set URL
CURLOPT_NOBODY => true, // do a HEAD request only
CURLOPT_FOLLOWLOCATION => true // follow location headers
CURLOPT_TIMEOUT => $timeout); // set timeout
如果您不必 curl ,您也可以使用标准的 PHP http 包装器(甚至可能在内部 curl )来执行此操作。示例代码:
$url = 'http://example.com/';
$code = FALSE;
$options['http'] = array(
'method' => "HEAD"
);
$context = stream_context_create($options);
$body = file_get_contents($url, NULL, $context);
foreach($http_response_header as $header)
{
sscanf($header, 'HTTP/%*d.%*d %d', $code);
}
echo "Status code (after all redirects): $code<br>\n";
另见HEAD first with PHP Streams .
一个相关的问题是How can one check to see if a remote file exists using PHP? .
关于PHP CURL 跟随重定向获取 HTTP 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8681915/