Skip to content

Using Bit.ly PHP API

URL shortening services became really popular after Twitter went mainstream. The leader in URL shortening services is definitely Bit.ly. In this tutorial i will briefly describe how to use it’s API to autmoatically sorten an URL address.

Signup for Bit.ly API key

Before we can do anything we need to signup for bit.ly api key, you can do it here http://bit.ly/a/sign_up, once you’re done you can find your key at http://bit.ly/a/your_api_key

Hint if you don’t feel like signing up you can use Bit.ly demo api key and password, but keep in mind that it shouldn’t be used in production. Login:bitlyapidemo, ApiKey=R_0da49e0a9118ff35f52f629d2d71bf07

Shortening URL with PHP and Bit.ly

Bit.ly has simple RESTful API so it’s easy to use it, in fact the whole script can be written in just one function.

function bitly_shorten($url)
{
    $query = array(
        "version" => "2.0.1",
        "longUrl" => $url,
        "login" => API_LOGIN, // replace with your login
        "apiKey" => API_KEY // replace with your api key
    );
 
    $query = http_build_query($query);
 
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://api.bit.ly/shorten?".$query);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
    $response = curl_exec($ch);
    curl_close($ch);
 
    $response = json_decode($response);
 
    if($response->errorCode == 0 && $response->statusCode == "OK") {
        return $response->results->{$url}->shortUrl;
    } else {
        return null;
    }
}

That’s it just copy and paste this code into your project.

BTW. I noticed that it’s possible to use custom domain names, instead of bit.ly or j.mp, however i did not find anything about it in Bit.ly v3 API, anyone can put some light on this? If yes, please post in the comments.

Published inGeneral