dougai0138
dougai0138
2013-09-26 19:31

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

已采纳

I want to get the video ID of a Youtube URL, but often the URL is condensed into a Tiny URL when being shared.

For example, I have a script that gets the Youtube video's thumbnail based on its video ID =

<?php $vlog = "OeqlkEymQ94"; ?>
<img src="http://img.youtube.com/vi/<?=$vlog;?>/0.jpg" alt="" />

This is easy to get when the URL I'm extracting it from is

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

but sometimes the URL is a tiny URL so I have to figure out how to return the real URL so I can use it.

http://tinyurl.com/kmx9zt6

Is it possible to retreive the real URL of a URL through PHP?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongxi5423 dongxi5423 8年前

    You could use get_headers() or cURL to grab the Location header:

    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;
    }
    

    Usage:

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

    Note: It's a slightly modified version of the gist here.

    点赞 评论 复制链接分享
  • dpsyssiv90846 dpsyssiv90846 8年前

    For future reference, I used a much simpler function because my Tiny URL's were always going to resolve to Youtube, and the headers were almost always the same :

    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;
    }
    

    usage -

    echo getFullURL('http://tinyurl.com/kmx9zt6');
    
    点赞 评论 复制链接分享

为你推荐