2

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

4

4 回答 4

12

您可以使用 CURL 来扩展短 URL。

尝试这个:

    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);.

  • 基督教
于 2010-12-21T02:03:13.450 回答
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

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

于 2010-12-21T02:00:09.843 回答
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);
  })
于 2016-01-04T21:27:22.583 回答
0

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

于 2011-12-15T14:39:48.047 回答