Following Redirects in PHP
Recently I have found that PHP sometimes doesn't follow redirects (e.g. the get_headers() function). So I wrote this quick function to follow a url's redirects to a certain depth:
/*
* @summary Follows a chain of redirects and returns that last url in the sequence.
*
* @param $url - The url to start at.
* @param $maxdepth - The maximum depth to which to travel following redirects.
*
* @returns The url at the end of the redirect chain.
*/
function follow_redirects($url, $maxdepth = 10, $depth = 0)
{
//return the current url if we have hit the maximum depth
if($depth >= $maxdepth)
return $url;
//download the headers from the url and make all the keys lowercase
$headers = get_headers($url, true);
$headers = array_change_key_case($headers);
//we have a redirect if the `location` header is set
if(isset($headers["location"]))
{
return follow_redirects($headers["location"], $maxdepth, $depth + 1);
}
else
{
return $url;
}
}
For example, you could do this:
follow_redirects("https://example.com/some/path", 5);
That would follow the redirects, starting at https://example.com/some/path, to a maximum depth of 5 urls.
When I learn networking in C♯ (and if it doesn't follow redirects), I will rewrite this function in C♯ for you.