简体   繁体   中英

How to get true address of a shortened URL in PHP?

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?

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

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");
?>
<?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');
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM