Create short links using bit.ly from php

bit.ly is a simple url shortner which has an api , which can be called from within php to shorten links.

Code :

function get_short_url($url) 
{
	$bitly_login = "your_login_name";
	$bitly_apikey = "your_api_key";
	
	$api_call = file_get_contents("http://api.bit.ly/shorten?version=2.0.1&longUrl=".$url."&login=".$bitly_login."&apiKey=".$bitly_apikey);
	
	$bitlyinfo=json_decode(utf8_encode($api_call),true);
	
	if ($bitlyinfo['errorCode'] == 0) 
	{
		return $bitlyinfo['results'][urldecode($url)]['shortUrl'];
	} 
	else 
	{
		return false;
	}
}

The above function can be used to shorten a big url , as :

if ($shortlink = get_short_url("http://www.google.com/")) 
{
    echo $shortlink;
} 
else 
{
    die("An error shortening the url");
}

The function needs an api key. To get your api key simply register at bit.ly then go to My Account and get your api key.






Last Updated On : 30th June 2009

Subscribe to get updates delivered to your inbox

About Silver Moon

Php developer, blogger and Linux enthusiast. He can be reached at [email protected]. Or find him on

Leave a comment