Snippet: Bit.ly URL Generation

Posted on Monday 17th October 2011 by Andy Mills

Share this:
  • Share this on Facebook
  • Share this on Twitter
  • Share this on Digg
  • Share this on Del.icio.us
  • Share this on MySpace
  • Share this on tumblr

When making this blog, I thought it would be a cool idea to provide Bit.ly short URLs for each of the posts, so people could tweet them etc.  Rather than manually creating a link for each post, however, I figured I could use the Bit.ly API to autogenerate the links when a new post was created, and then insert it into the database with the rest of the posts.

After a bit of tweaking from PHP functions found on the internet (I seem to have picked all of the ones that didn't work), I ended up with this:

function get_bitly_url($long_url)
{
	// API Key for Bit.ly
	$API_Key = 'your_api_key_here';

	// Your Bit.ly Username
	$Login = 'your_username_here';

	// The browser-friendly URL String
	$Safe_URL = urlencode($long_url);
	
	// Build the URL
	$Bit_URL = "http://api.bit.ly/v3/shorten/?login=$Login&apiKey=$API_Key
			&uri=$Safe_URL&format=txt";
	
	// Set the REST Service URL
	$Curl = curl_init($Bit_URL);
	curl_setopt($Curl, CURLOPT_RETURNTRANSFER, true);
	
	// Return the Result
	return curl_exec($Curl);
}

This function takes whatever long URL you put into it and returns the shortened Bit.ly URL.

Since writing this, I've been reading into the tonne of other features available from the Bit.ly API, which I will post on here soon.