Code snippet #2 – Shorten Links Using Bit.ly

Following the first snippet, here is another small one to shorten a link using Bit.ly. I chose Bit.ly over other link shortening services due to a simple reason: Twitter uses it as default (by now).

Code snippet #2 – Shorten Links Using Bit.ly

Purpose

Create a shortened URL using Bit.ly. This is extremely useful for your visitors, as they don’t have to look any further – just grab it to use right away.

Requirements

  • A Bit.ly account (and API key). You can create one for free at their site in seconds. Once logged in, head to Account section and look for a long ugly string starting with “R_”.
  • PHP 5 >= 5.2.0. Your host doesn’t support PHP 5? Claim your money back and find another host.

The Code

function get_shortened_url($url)
{
    $bitly_api_key = 'YOUR KEY HERE';
    $bitly_username = 'YOUR BIT.LY USERNAME HERE';
    $data = file_get_contents("http://api.bit.ly/shorten?version=2.0.1&longUrl=$url&login=$bitly_username&apiKey=$bitly_api_key");

    $data = json_decode(utf8_encode($data));

    if ($data->errorCode)
    {
        return false;
    } 

    return $data->results->$url->shortUrl;
}

// now use it
echo get_shortened_url('http://www.example.com/this-is-a-stupid-long-long-long-url.html');

// how about WordPress?
// Just place the function above somewhere in your functions.php theme page and then

// 1. inside The Loop
echo get_shortened_url(get_permalink());

// 2. outside The Loop
echo get_shortened_url(get_permalink($post->ID));

  • Nice thanks, works well :)

You can follow any responses to this entry through the RSS 2.0 feed.