如何在PHP中获得缩短URL的真实地址


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

有什么方法可以让另一个(缩短的)URL指向URL吗
例如,我缩短了http://www.stackoverflow.com到此URL:http://tinyurl.com/5b2su2

我需要一个PHP函数,比如:

getTrueURL($shortened_url)
{
 // ?
}

当调用getTrueURL('http://tinyurl.com/5b2su2')时,它应该返回'http://stackoverflow.com'。我该怎么做?

附言:如果在服务器端无法实现,我也可以使用JavaScript解决方案。

我想,你需要这个:

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