Skip to content

Create Bit.ly Short URLs Using PHP?

One of the more popular and powerful URL shortening services is Bit.ly. Bitly offers simple and powerful API to generate short URL. To use this API you have to signup for an API key. Bitly offers it free for it’s all users. If you want, you can get it from Bitly’s home page. Here’s an example to create a short URL using PHP remotely.

function bitly_url($url,$login,$appkey,$format = 'xml',$version = '2.0.1')
{
	$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;
	
	$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    curl_close($ch);

	if(strtolower($format) == 'json')
	{
		$json = @json_decode($data,true);
		return $json['results'][$url]['shortUrl'];
	}
	else //xml
	{
		$xml = simplexml_load_string($data);
		return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
	}
}

/* usage demo */
$short = bitly_url('http://www.arjun.net.in','','','json');
echo 'The short URL is:  '.$short; 

// returns:  http://bit.ly/197MvCA
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments