Shortening URLs in PHP with the 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. 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 username and yourapikey with your API key, which can be found at

function shorten_url($url) {
    if (!$url) { return false; }
    $bitly_username = 'yourusername';
    $bitly_api_key = 'yourapikey';
    $url = urlencode(trim($url));
    $api_address = ''.$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);
    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('');

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



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 of use.