我无法使用从 here 获得的以下函数成功地将双重缩短的 URL 转换为扩展的 URL :
function doShortURLDecode($url) {
$ch = @curl_init($url);
@curl_setopt($ch, CURLOPT_HEADER, TRUE);
@curl_setopt($ch, CURLOPT_NOBODY, TRUE);
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = @curl_exec($ch);
preg_match('/Location: (.*)\n/', $response, $a);
if (!isset($a[1])) return $url;
return $a[1];
}
当我得到的扩展 URL 又是一个缩短的 URL,它有它的扩展 URL 时,我遇到了麻烦。
在通过两个 URL 缩短服务后,我如何获得最终的扩展 URL?
最佳答案
自 t.co
通过使用 JavaScript 和/或 <meta>
使用 HTML 重定向重定向我们需要先获取它的内容。然后提取 bit.ly
从它的 URL 执行 HTTP header 请求以获取最终位置。此方法不依赖于在服务器上启用 cURL 并使用所有 native PHP5 函数:
已测试并正常工作!
function large_url($url)
{
$data = file_get_contents($url); // t.co uses HTML redirection
$url = strtok(strstr($data, 'http://bit.ly/'), '"'); // grab bit.ly URL
stream_context_set_default(array('http' => array('method' => 'HEAD')));
$headers = get_headers($url, 1); // get HTTP headers
return (isset($headers['Location'])) // check if Location header set
? $headers['Location'] // return Location header value
: $url; // return bit.ly URL instead
}
// DEMO
$url = 'http://t.co/dd4b3kOz';
echo large_url($url);
关于php - 从双重缩短的 URL 获取最终 URL (t.co -> bit.ly -> final),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14620546/