PHP CURL 跟随重定向获取 HTTP 状态

标签 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 状态代码?

最佳答案

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/

相关文章:

php - 从mysql数据库中的两个不同行中减去值

php - 重定向 301 相对于 php 中的 url

ruby-on-rails - 使用cURL进行设备身份验证

某些版本的 IE 中的 JavaScript 重定向问题

node.js - 如何在 res.redirect ('/' )之后执行操作或发送信息?

php - 有没有办法执行这个 CURL 请求而不打印响应?

java - "Curl -F"Java 等价物

php - Contenteditable div 高度限制

php Gmagick 保存 jpeg 质量

javascript - Google Maps API 必须单击标记两次才能动态显示图像