phpurl-routingbit.ly

Determine Final Destination of a Shortened URL in PHP?


How can I do this in PHP? e.g.

bit.ly/f00b4r ==> http://www.google.com/search?q=cute+kittens

In Java, the solution is this:

You should issue a HEAD request to the url using a HttpWebRequest instance. In the returned HttpWebResponse, check the ResponseUri.

Just make sure the AllowAutoRedirect is set to true on the HttpWebRequest instance (it is true by default). (Thx, casperOne)

And the code is

private static string GetRealUrl(string url)
{
    WebRequest request = WebRequest.Create(url);
    request.Method = WebRequestMethods.Http.Head;
    WebResponse response = request.GetResponse();
    return response.ResponseUri.ToString();
}

(Thx, Fredrik Mork)

But I want to do it in PHP. HOWTO? :)


Solution

  • CREDIT GOES TO http://forums.devshed.com/php-development-5/curl-get-final-url-after-inital-url-redirects-544144.html

    function get_web_page( $url ) 
    { 
        $options = array( 
            CURLOPT_RETURNTRANSFER => true,     // return web page 
            CURLOPT_HEADER         => true,    // return headers 
            CURLOPT_FOLLOWLOCATION => true,     // follow redirects 
            CURLOPT_ENCODING       => "",       // handle all encodings 
            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 ); 
    
        //$header['errno']   = $err; 
       // $header['errmsg']  = $errmsg; 
        //$header['content'] = $content; 
        print($header[0]); 
        return $header; 
    }  
    $thisurl = "http://www.example.com/redirectfrom";
    $myUrlInfo = get_web_page( $thisurl ); 
    echo $myUrlInfo["url"];