PHP或JS中最好的方法是扩展像Bitly,Tinyurl这样的缩短URL来查找原始URL?

时间:2010-12-21 01:53:58

标签: php javascript bit.ly url-shortener

我正在使用Twitter和Facewbook API来使用bit.ly或类似TinyURL的服务来提取可能包含缩短URL的帖子。我需要进行实时扩展以获取原始网址,然后将该网址中的内容提取到我的应用中。

4 个答案:

答案 0 :(得分:12)

您可以使用CURL扩展短网址。

试试这个:

    function traceUrl($url, $hops = 0)
    {
        if ($hops == MAX_URL_HOPS)
        {
            throw new Exception('TOO_MANY_HOPS');
        }

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_NOBODY, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $r = curl_exec($ch);

        if (preg_match('/Location: (?P<url>.*)/i', $r, $match))
        {
            return traceUrl($match['url'], $hops + 1);
        }

        return rtrim($url);
    }

您可以使用此功能traceUrl('http://bit.ly/example')。这个函数是递归的,因为它甚至可以找到缩短的短网址(如果它发生的话)。确保将MAX_URL_HOPS设置为常量。我使用define('MAX_URL_HOPS', 5);

  • 基督教

答案 1 :(得分:7)

您可以使用PHP和CURL连接到URL并获取Location参数:

以下是回来的内容 -

> $ curl -I http://bit.ly/2V6CFi
> HTTP/1.1 301 Moved Server:
> nginx/0.7.67 Date: Tue, 21 Dec 2010
> 01:58:47 GMT Content-Type: text/html;
> charset=utf-8 Connection: keep-alive
> Set-Cookie:
> _bit=4d1009d7-00298-02f7f-c6ac8fa8;domain=.bit.ly;expires=Sat
> Jun 18 21:58:47 2011;path=/; HttpOnly
> Cache-control: private; max-age=90
> Location: http://www.google.com/
> MIME-Version: 1.0

Content-Length: 284

因此,您可以在标题中查找Location参数,以查看页面实际所在的位置。

答案 2 :(得分:2)

使用nodejs,您可以使用模块 request

var request = require('request');
var shortUrl = 'the url that is shortened'
request({method: 'HEAD', url: shortUrl, followAllRedirects: true}, 
  function(err, response, body){
     console.log(response.request.href);
  })

答案 3 :(得分:0)

我发现了一个能够做到这一点的php库,它可能很有用。 看看:https://launchpad.net/longurl