How to get final URL after following HTTP redirections in pure PHP?

function getRedirectUrl ($url) {
    stream_context_set_default(array(
        'http' => array(
            'method' => 'HEAD'
        )
    ));
    $headers = get_headers($url, 1);
    if ($headers !== false && isset($headers['Location'])) {
        return $headers['Location'];
    }
    return false;
}

Additionally…

As was mentioned in a comment, the final item in $headers['Location'] will be your final URL after all redirects. It’s important to note, though, that it won’t always be an array. Sometimes it’s just a run-of-the-mill, non-array variable. In this case, trying to access the last array element will most likely return a single character. Not ideal.

If you are only interested in the final URL, after all the redirects, I would suggest changing

return $headers['Location'];

to

return is_array($headers['Location']) ? array_pop($headers['Location']) : $headers['Location'];

… which is just if short-hand for

if(is_array($headers['Location'])){
     return array_pop($headers['Location']);
}else{
     return $headers['Location'];
}

This fix will take care of either case (array, non-array), and remove the need to weed-out the final URL after calling the function.

In the case where there are no redirects, the function will return false. Similarly, the function will also return false for invalid URLs (invalid for any reason). Therefor, it is important to check the URL for validity before running this function, or else incorporate the redirect check somewhere into your validation.

Leave a Comment