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?
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.
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');