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.