2

私は Twitter と Facebook の 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')。この関数は、短縮された短い URL も検索するという意味で再帰的です (発生した場合)。必ず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

そのため、ヘッダーの 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 に答える