PHP CURL跟踪重定向以获取HTTP状态 [英] PHP CURL follow redirect to get HTTP status

查看:1297
本文介绍了PHP CURL跟踪重定向以获取HTTP状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为网页的HTTP代码创建了以下PHP函数。

I created the following PHP function to the HTTP code of a webpage.

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

How can I modify this function to follow 301 & 302 redirects (possibility multiple redirects) and get the final HTTP status code?

推荐答案

设置 CURLOPT_FOLLOWLOCATION code>。

set CURLOPT_FOLLOWLOCATION to 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包装器(这可能甚至卷曲然后在内部)。示例代码:

If you're not bound to curl, you can do this with standard PHP http wrappers as well (which might be even curl then internally). Example code:

$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

相关问题是如何使用PHP检查远程文件是否存在?

这篇关于PHP CURL跟踪重定向以获取HTTP状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆