PHP CURL遵循重定向以获取HTTP状态

时间:2011-12-30 16:59:03

标签: php redirect curl http-status-code-301

我在网页的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状态代码?

1 个答案:

答案 0 :(得分:17)

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

如果你没有被束缚,你也可以使用标准的PHP http包装器(这可能甚至在内部卷曲)。示例代码:

$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?