Question

Is there any way that I can get the URL pointed by another (shortened) URL?
For example, I have shortened http://www.stackoverflow.com to this URL: http://tinyurl.com/5b2su2

I need a function in PHP like:

getTrueURL($shortened_url)
{
 // ?
}

That should return 'http://stackoverflow.com' when getTrueURL('http://tinyurl.com/5b2su2') is called. How can I do this?

P.S: If it is impossible in server-side, I can also use a JavaScript solution as well.

Was it helpful?

Solution

I think, you need this one:

<?php
function getTrueURL($url)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    $data = curl_getinfo($ch);
    return $data["url"];
}

echo getTrueURL("http://tinyurl.com/5b2su2");
?>

OTHER TIPS

<?php



function tinyurl_reverse($szAddress)
{
    $szAddress = explode('.com/', $szAddress);
    $szAddress = 'http://preview.tinyurl.com/'.$szAddress[1];
    $szDocument = file_get_contents($szAddress);
    preg_match('~redirecturl" href="(.*)">~i', $szDocument, $aMatches);

    if(isset($aMatches[1]))
    {
        return $aMatches[1];
    }

    return null;
}

echo tinyurl_reverse('http://tinyurl.com/5b2su2');
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top