5

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

1 Answer 1

18

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

Sign up to request clarification or add additional context in comments.

1 Comment

great answer. in my case i needed the final location, so doing a sscanf($header, 'Location: %s', $loc); did the trick. thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.