Skip navigation

Blog > Automatic link shortening

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:

<code>

function BitlyCurlGetResult($url)

{

$ch = curl_init();

$timeout = 5;

curl_setopt($ch,CURLOPT_URL,$url);

curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);

$data = curl_exec($ch);

curl_close($ch);

return $data;

}

</code>

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:

<code>

function GetShortURL()

{

$aConnectURL = 'http://api.bit.ly/v3/shorten?login=' . YOUR_BITLY_USERNAME . '&apiKey=' . YOUR_BITLY_APIKEY . '&uri=' . urlencode(http://www.somewebsiteurl.com) . '&format=txt';

return BitlyCurlGetResult($aConnectURL);

}

</code>

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.