Shorten URL using Bitly URL Shorten API


My previous tutorial was about Shorten URL using Google URL Shortener API. In this tutorial I will show you How to Shorten URL using Bitly URL Shorten API with PHP. Bitly is one of the most powerful and popular URL shorten and bookmark service. It offers simple and powerful API to generate shorten URL from long URLs.

To use Bitly URL Shorten API you have to signup for an API key. Bitly offers it free for it’s all users. You can get the API key from https://bitly.com/a/your_api_key after login. I have created a class BitlyAPI to shorten long URL and expand short URLs. Following is a simple example of shorten a long URL and expand a short URL.

class BitlyAPI
{
    var $apiURL = 'http://api.bit.ly/v3/';
    var $apiStr = '';
 
    function __construct($username, $apiKey){
        $this->apiStr = 'login=' . $username;
        $this->apiStr .= '&apiKey=' . $apiKey;
        $this->apiStr .= '&format=json';
    }
 
    /* Shorten Long URL */
    function shorten($uri){
        $this->apiStr .= '&uri=' . urlencode($uri);
        $query = $this->apiURL . 'shorten?' . $this->apiStr;
        $data = $this->curl($query);
        
        $json = json_decode($data);
        return isset($json->data->url) ? $json->data->url : '';
    }
 
    /* Expand Short URL */
    function expand($uri){
        $this->apiStr .= '&shortUrl='.urlencode($uri);
        $query = $this->apiURL . 'expand?' . $this->apiStr;
        $data = $this->curl($query);
        
        $json = json_decode($data);
        return isset($json->data->expand[0]->long_url) ? $json->data->expand[0]->long_url : '';
    }
 
    /* Send CURL Request */
    function curl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false );
        
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}

Now you can use above class as following:

$username = 'username';
$key = 'your api key';
$api = new BitlyAPI($username, $key);

// Shorten a URL
$shortURL = $api->shorten("http://www.tricksofit.com");
echo "Short URL : ".$shortURL;

echo "<br>";
// Expand a URL
$longURL = $api->expand($shortURL);
echo "Long URL : ".$longURL;

You will get following result:
Short URL : http://bit.ly/1HPAf9i
Long URL : http://www.tricksofit.com/

Hope this tutorial will help you shorten URL using Bitly URL Shorten API.