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?
The curl_setopt() function will set options for a CURL session identified by the ch parameter. The option parameter is the option you want to set, and the value is the value of the option given by the option. The value should be a long for the following options (specified in the option parameter):
cURL is a PHP library and command-line tool (similar to wget) that allows you to send and receive files over HTTP and FTP. You can use proxies, pass data over SSL connections, set cookies, and even get files that are protected by a login.
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?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With