bea*_*ive 2 javascript php bit.ly url-shortener
我正在使用Twitter和Facewbook API来使用bit.ly或类似TinyURL的服务来提取可能包含缩短URL的帖子.我需要进行实时扩展以获取原始网址,然后将该网址中的内容提取到我的应用中.
Chr*_*rey 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);
}
Run Code Online (Sandbox Code Playgroud)
你可以这样使用这个功能traceUrl('http://bit.ly/example').这个函数是递归的,因为它甚至可以找到缩短的短网址(如果它发生的话).确保设置MAX_URL_HOPS常量.我用define('MAX_URL_HOPS', 5);.
您可以使用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
Run Code Online (Sandbox Code Playgroud)
因此,您可以在标头中查找Location参数,以查看页面实际所在的位置.