【问题标题】:How to get true address of a shortened URL in PHP?如何在 PHP 中获取缩短 URL 的真实地址?
【发布时间】:2013-08-17 11:46:26
【问题描述】:

有什么方法可以获取另一个(缩短的)URL 指向的 URL?
例如,我将http://www.stackoverflow.com 缩短为这个网址:http://tinyurl.com/5b2su2

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

getTrueURL($shortened_url)
{
 // ?
}

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

附注: 如果在服务器端不可能,我也可以使用 JavaScript 解决方案。

【问题讨论】:

标签: php javascript url url-shortener


【解决方案1】:

我想,你需要这个:

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

【讨论】:

  • 看起来不错,但在发出警告 curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set 后会回显“tinyurl.com/5b2su2”。我在网络主机上,所以我无法更改 php 配置..
  • 哦,我通过这里的解决方案解决了它:stackoverflow.com/questions/10835255/… 现在它与 stackoverflow.com 相呼应。谢谢!!
  • 我删除了我的一半答案,因为这要好得多。 +1,因为我什至不知道“curl_getinfo”的存在。
  • 嘿,我可以将它用于谷歌网址吗?喜欢这个:google.com.tr/…
  • 你可以使用parse_url
【解决方案2】:
<?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');
?>

【讨论】:

  • 我需要一个通用的方法,不仅适用于 tinyurl。还是谢谢!
  • @CengizFrostclaw:没有“通用方法”,因为所有这些服务都使用自己的算法。 “URL 缩短”不是 Internet URL 协议的一部分。
  • 如果您想要一个通用的解决方案,那么请尝试我作为对您问题的评论发布的 unshort.me API:它声称可以与 t.co (Twitter)、bit.ly、TinyURL、 Google goo.gl、Facebok fb.me、tr.im、Ow.ly 等
猜你喜欢
  • 2010-12-25
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-04
  • 2023-04-05
  • 2011-06-08
相关资源
最近更新 更多