【问题标题】:PHP CURL follow redirect to get HTTP statusPHP CURL 跟随重定向以获取 HTTP 状态
【发布时间】:2012-01-30 16:49:34
【问题描述】:

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

【问题讨论】:

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


【解决方案1】:

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?

【讨论】:

  • 很好的答案。在我的情况下,我需要最终位置,所以做 sscanf($header, 'Location: %s', $loc); 就可以了。谢谢!
猜你喜欢
  • 2012-05-04
  • 1970-01-01
  • 1970-01-01
  • 2015-12-07
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多