用PHP或JS扩展缩短的URL(例如Bitly,Tinyurl)以查找原始URL的最佳方法是什么? [英] What is the best way in PHP or JS to expand shortened URLs like Bitly, Tinyurl to find the original URL?
问题描述
我正在使用Twitter和Facewbook API使用类似于bit.ly或TinyURL的服务提取可能包含缩短的URL的帖子.我需要进行实时扩展以获取原始URL,然后将内容从该URL提取到我的应用中.
I am using the Twitter and Facewbook API to pull posts that potentially contain shortened URLs using bit.ly or TinyURL like services. I need to do a real-time expansion to get the original URL then pull content from that URL into my app.
推荐答案
您可以使用CURL扩展短网址.
You can use CURL to expand a short 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);
.
You can use this function as so traceUrl('http://bit.ly/example')
. This function is recursive in the sense that it will even find short urls that are shortened (if it ever happens). Make sure you set the MAX_URL_HOPS
constant. I use define('MAX_URL_HOPS', 5);
.
- 基督徒
这篇关于用PHP或JS扩展缩短的URL(例如Bitly,Tinyurl)以查找原始URL的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!