PHP CURL follow redirect to get HTTP status

2019-02-17 18:23发布

问题:

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;
}

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

回答1:

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

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";

See as well HEAD first with PHP Streams.

A related question is How can one check to see if a remote file exists using PHP?.