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

Viewed 43808

What I'd like to do is find out what is the last/final URL after following the redirections.

I would prefer not to use cURL. I would like to stick with pure PHP (stream wrappers).

Right now I have a URL (let's say http://domain.test), and I use get_headers() to get specific headers from that page. get_headers will also return multiple Location: headers (see Edit below). Is there a way to use those headers to build the final URL? or is there a PHP function that would automatically do this?

Edit: get_headers() follows redirections and returns all the headers for each response/redirections, so I have all the Location: headers.

6 Answers

Added to code from answers @xaav and @Houssem BDIOUI: 404 Error case and case when URL with no response. get_final_url($url) in that cases return strings: 'Error: 404 Not Found' and 'Error: No Responce'.

/**
 * get_redirect_url()
 * Gets the address that the provided URL redirects to,
 * or FALSE if there's no redirect,
 * or 'Error: No Responce',
 * or 'Error: 404 Not Found'
 *
 * @param string $url
 * @return string
 */
function get_redirect_url($url)
{
    $redirect_url = null;

    $url_parts = @parse_url($url);
    if (!$url_parts)
        return false;
    if (!isset($url_parts['host']))
        return false; //can't process relative URLs
    if (!isset($url_parts['path']))
        $url_parts['path'] = '/';

    $sock = @fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80), $errno, $errstr, 30);
    if (!$sock) return 'Error: No Responce';

    $request = "HEAD " . $url_parts['path'] . (isset($url_parts['query']) ? '?' . $url_parts['query'] : '') . " HTTP/1.1\r\n";
    $request .= 'Host: ' . $url_parts['host'] . "\r\n";
    $request .= "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36\r\n";
    $request .= "Connection: Close\r\n\r\n";
    fwrite($sock, $request);
    $response = '';
    while (!feof($sock))
        $response .= fread($sock, 8192);
    fclose($sock);

    if (stripos($response, '404 Not Found') !== false)
    {
        return 'Error: 404 Not Found';
    }

    if (preg_match('/^Location: (.+?)$/m', $response, $matches))
    {
        if (substr($matches[1], 0, 1) == "/")
            return $url_parts['scheme'] . "://" . $url_parts['host'] . trim($matches[1]);
        else
            return trim($matches[1]);

    } else
    {
        return false;
    }

}

/**
 * get_all_redirects()
 * Follows and collects all redirects, in order, for the given URL.
 *
 * @param string $url
 * @return array
 */
function get_all_redirects($url)
{
    $redirects = array();
    while ($newurl = get_redirect_url($url))
    {
        if (in_array($newurl, $redirects))
        {
            break;
        }
        $redirects[] = $newurl;
        $url = $newurl;
    }
    return $redirects;
}

/**
 * get_final_url()
 * Gets the address that the URL ultimately leads to.
 * Returns $url itself if it isn't a redirect,
 * or 'Error: No Responce'
 * or 'Error: 404 Not Found',
 *
 * @param string $url
 * @return string
 */
function get_final_url($url)
{
    $redirects = get_all_redirects($url);
    if (count($redirects) > 0)
    {
        return array_pop($redirects);
    } else
    {
        return $url;
    }
}

After hours of reading Stackoverflow and trying out all custom functions written by people as well as trying all the cURL suggestions and nothing did more than 1 redirection, I managed to do a logic of my own which works.

$url = 'facebook.com';
// First let's find out if we just typed the domain name alone or we prepended with a protocol 
if (preg_match('/(http|https):\/\/[a-z0-9]+[a-z0-9_\/]*/',$url)) {
    $url = $url;
} else {
    $url = 'http://' . $url;
    echo '<p>No protocol given, defaulting to http://';
}
// Let's print out the initial URL
echo '<p>Initial URL: ' . $url . '</p>';
// Prepare the HEAD method when we send the request
stream_context_set_default(array('http' => array('method' => 'HEAD')));
// Probe for headers
$headers = get_headers($url, 1);
// If there is a Location header, trigger logic
if (isset($headers['Location'])) {
    // If there is more than 1 redirect, Location will be array
    if (is_array($headers['Location'])) {
        // If that's the case, we are interested in the last element of the array (thus the last Location)
        echo '<p>Redirected URL: ' . $headers['Location'][array_key_last($headers['Location'])] . '</p>';
        $url = $headers['Location'][array_key_last($headers['Location'])];
    } else {
        // If it's not an array, it means there is only 1 redirect
        //var_dump($headers['Location']);
        echo '<p>Redirected URL: ' . $headers['Location'] . '</p>';
        $url = $headers['Location'];
    }
} else {
    echo '<p>URL: ' . $url . '</p>';
}
// You can now send get_headers to the latest location
$headers = get_headers($url, 1);
Related