We recently had a requirement to extend our content management system to allow posting to Twitter. Each post needed to have a link back to the site and to save space we decided to use the bitly (http://bit.ly) shortening link service to create shortened links to enable extra characters to be entered into the Tweet.
Bitly includes an API that allows you to connect to their service and automatically shorten links. It is actually a very simple process. Before you can access the API you will need to sign up for an account on the bitly website, once you have done this you will be issued with an API key.
First curl needs to be used to connect to bitly:
Next all you need to do is to create a link with your bitly username, api key and link to shorten, then call the function above to have your shortened link returned:
You will notice an extra field added to the url called 'format'. If this is set to 'txt' then it will return the shortened link in plain text so it is ready to use straight away. If you don't include this field then you will get an array returned with a lot more information about the bitly shortened url including the shortened url.
If you change the ConnectURL from 'shorten' to 'expand' then the original url will be returned. This could be useful in certain circumstances.