Code

Shortening URLs in PHP with the bit.ly API

If you have a Twitter application, chances are that you'll need a URL shortening service to generate links for it. You can either recreate the wheel and do this on your own or, instead, plug into one of the many services that will do this for you for free. Bit.ly is one of those services and has a really simple to use API. I've made it even easier here by creating this PHP function that does all the work for you. Simply replace yourusername with your bit.ly username and yourapikey with your API key, which can be found at http://bit.ly/a/your_api_key.

function shorten_url($url) {
    if (!$url) { return false; }
    $bitly_username = 'yourusername';
    $bitly_api_key = 'yourapikey';
    $url = urlencode(trim($url));
    $api_address = 'http://api.bitly.com/v3/shorten?login='.$bitly_username.'&apiKey='.$bitly_api_key.'&longUrl='.$url.'&format=txt';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_address);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    if (!$response) { return false; }
    elseif (substr($response,0,7) != 'http://') { return false; }
    else { return trim(strip_tags($response)); }
}

With the above function defined, it's super simple to get your shortened URL:

echo shorten_url('http://www.inkplant.com/code/');
//returns http://bit.ly/fdk8GQ

There are more advanced elements of the API available should you need them. For more information, see bit.ly's API Documentation.



2 Comments

mido
July 16, 2013, 9:07 pm
how to get a different shortened url every time when i reload the page ?? please help me
samir
February 20, 2014, 4:28 am
Thanks!

Leave a Comment

Name
Email
Website
Comment
Name and email are required. Your email will not be published.

This post was published on March 19th, 2011 by Robert James Reese in PHP.

Before using any of the code or other content in this post, you must read and agree to our Terms & Conditions.

Copyright © 2014, Ink Plant. All rights reserved.