获取一个小URL的真实URL并存储为PHP变量

时间:2013-09-26 19:31:16

标签: php url youtube

我想获取Youtube网址的视频ID,但在分享时,网址通常会缩小为Tiny网址。

例如,我有一个脚本可以根据视频ID =

获取Youtube视频的缩略图
<?php $vlog = "OeqlkEymQ94"; ?>
<img src="http://img.youtube.com/vi/<?=$vlog;?>/0.jpg" alt="" />

当我从中提取URL时,这很容易获得

http://www.youtube.com/watch?v=OeqlkEymQ94

但有时URL是一个很小的URL,所以我必须弄清楚如何返回真实的URL,以便我可以使用它。

http://tinyurl.com/kmx9zt6

是否可以通过PHP检索URL的真实URL?

2 个答案:

答案 0 :(得分:1)

您可以使用get_headers()cURL来抓取Location标题:

function getFullURL($url) {
    $headers = get_headers($url);
    $headers = array_reverse($headers);
    foreach($headers as $header) {
        if (strpos($header, 'Location: ') === FALSE) {
            $url = str_replace('Location: ', '', $header);
            break;
        }
    }    
    return $url;
}

用法:

echo getFullURL('http://tinyurl.com/kmx9zt6');

注意:这是gist here的略微修改版本。功能

答案 1 :(得分:0)

为了将来的参考,我使用了一个更简单的功能,因为我的Tiny URL总是会解析为Youtube,并且标题几乎总是相同的:

function getFullURL($url) {
    $headers = get_headers($url);
    $url = $headers[4]; //This is the location part of the array
    $url = str_replace('Location: ', '', $url);
    $url = str_replace('location: ', '', $url);  //in my case the location was lowercase, but it can't hurt to have both
    return $url;
}

用法 -

echo getFullURL('http://tinyurl.com/kmx9zt6');