Expanding Short URLs with PHP: expand_url PHP function
May 18th, 2010

URL shortening services work by redirecting a users browser from the shortened URL to the actual target URL. Some of these services provide means of reversing the shortening process. Some provide API methods for this.
The following function will take a shortened URL, from any service, and return the original URL. As it works by inspecting the HTTP redirect headers it is 100% service independent, and does away with the need to query the API of services like bit.ly for url expansion.
function expand_url($url) {
// Use curl to fetch the HTTP Headers
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1); // just the header
curl_setopt($ch, CURLOPT_NOBODY, 1); // not the body
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
preg_match('/Location: (.*)\n/', $output, $matches);
// if no redirect header then return the original url
return isset($matches[1]) ? $matches[1] : $url;
}
A Simpler PHP 5 Version
I’ve used curl for portability. PHP 5 has a built in get_headers function which you could use to simplify the function a little. It would look something like this:
function expand_url($url) {
$h = get_headers($url);
// if no redirect header then return the original url
return isset($h['Location']) ? $h['Location'] : $url;
}
Creating Short URLs With PHP
For creating short urls on the fly with PHP see: PHP shorten_url function

