HappyDeveloper
HappyDeveloper

Reputation: 12805

How to get the real URL after file_get_contents if redirection happens?

I'm using file_get_contents() to grab content from a site, and amazingly it works even if the URL I pass as argument redirects to another URL.

The problem is I need to know the new URL, is there a way to do that?

Upvotes: 49

Views: 56347

Answers (5)

kostikovmu
kostikovmu

Reputation: 699

I use get_headers($url, 1);

In my case redirect url in get_headers($url, 1)['Location'][1];

Upvotes: 1

Martin Prikryl
Martin Prikryl

Reputation: 202262

A complete solution using the bare file_get_contents (note the in-out $url parameter):

function get_url_contents_and_final_url(&$url)
{
    do
    {
        $context = stream_context_create(
            array(
                "http" => array(
                    "follow_location" => false,
                ),
            )
        );

        $result = file_get_contents($url, false, $context);

        $pattern = "/^Location:\s*(.*)$/i";
        $location_headers = preg_grep($pattern, $http_response_header);

        if (!empty($location_headers) &&
            preg_match($pattern, array_values($location_headers)[0], $matches))
        {
            $url = $matches[1];
            $repeat = true;
        }
        else
        {
            $repeat = false;
        }
    }
    while ($repeat);

    return $result;
}

Note that this works only with an absolute URL in the Location header. If you need to support relative URLs, see PHP: How to resolve a relative url.

For example, if you use the solution from the answer by @Joyce Babu, replace:

            $url = $matches[1];

with:

            $url = getAbsoluteURL($matches[1], $url);

Upvotes: 6

alex
alex

Reputation: 490233

You might make a request with cURL instead of file_get_contents().

Something like this should work...

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$a = curl_exec($ch);
if(preg_match('#Location: (.*)#', $a, $r))
 $l = trim($r[1]);

Source

Upvotes: 20

Jakub Zalas
Jakub Zalas

Reputation: 36191

If you need to use file_get_contents() instead of curl, don't follow redirects automatically:

$context = stream_context_create(
    array(
        'http' => array(
            'follow_location' => false
        )
    )
);

$html = file_get_contents('http://www.example.com/', false, $context);

var_dump($http_response_header);

Answer inspired by: How do I ignore a moved-header with file_get_contents in PHP?

Upvotes: 73

Renaud
Renaud

Reputation: 16501

Everything in one function:

function get_web_page( $url ) {
    $res = array();
    $options = array( 
        CURLOPT_RETURNTRANSFER => true,     // return web page 
        CURLOPT_HEADER         => false,    // do not return headers 
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects 
        CURLOPT_USERAGENT      => "spider", // who am i 
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect 
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect 
        CURLOPT_TIMEOUT        => 120,      // timeout on response 
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects 
    ); 
    $ch      = curl_init( $url ); 
    curl_setopt_array( $ch, $options ); 
    $content = curl_exec( $ch ); 
    $err     = curl_errno( $ch ); 
    $errmsg  = curl_error( $ch ); 
    $header  = curl_getinfo( $ch ); 
    curl_close( $ch ); 

    $res['content'] = $content;     
    $res['url'] = $header['url'];
    return $res; 
}  
print_r(get_web_page("http://www.example.com/redirectfrom")); 

Upvotes: 18

Related Questions