Skip to content

Create Short URLs Using PHP?

One of the more popular and powerful URL shortening services is 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 = ''.$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);

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

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

// returns:
0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments