PHP Function for Expanding Bit.ly Short URLs
Bit.ly is quickly becoming the defacto standard for URL shortening, and offers a pretty good API for developers. I was looking for a way to expand bit.ly short URLs to the original, long URLs they redirect to, and ended up writing this function:
// given a bit.ly url, passed in as $url, return the long form version of the url
function expand($url) {
// split the url into parts to obtain the hash at the end
$parts = split('/', $url);
// obtain the hash part of the URL, to be used later
$hash = $parts[count($parts) - 1];
// our authentication information. replace with your info
$login = "YOURUSERNAME";
$api = "YOURAPIKEY";
// the url for our CURL session. response will be in json format
$url = "http://api.bit.ly/expand?version=2.0.1&shortUrl={$url}&login={$login}&apiKey={$api}&format=json";
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, TRUE);
$ci = curl_exec($c);
curl_close($c);
// decodes the json string and turn it into a variable
$response = json_decode($ci);
// use the hash obtained earlier to return the long URL
return $response->results->$hash->longUrl;
}
Pretty simple, huh? Simply replace the $login and $api key with your own values to get it working. If you don’t have an API get, registered an account at bit.ly and you’ll find an API key on your account page.
To get the expanded url from any bit.ly url, simply pass the short bit.ly url to the function.
$longurl = expand(“http://bit.ly/urlhash”);

