Tuesday, April 20, 2010

PHP wrapper for bit.ly API

bit.ly is one of the sites which allows you to shorten the long URLs. This method of sharing URLs is becoming very popular these days.
Currently, bit.ly provides a full fledged API to access its features.

I have created a PHP wrapper for the api so that one can use it in his applications. The wrapper takes the url and gives the required data in an array format.

Structure of the wrapper :
|--- bit_ly class

Requirements :
  • curl library to be installed on the server. PHP4 and 5 has it by default. You will have to enable it. This blog explains how to enable cURL in XAMPP.
  • bit.ly login and API key. If you dont have API key register here and get your own key

To use this in your php file :
  • Download wrapper from here. Extract it and put it on your server.
  • add include ('path/bit_ly_php_api.php') in your php file
  • create bit_ly class instance (say bit)
$bit = new bit_ly('bit.ly login', 'bit.ly api key')
  • configure the proxy if needed

Now you can perform following operations :
  • Shorten a long URL:
$short = $bit->shortenURL('www.cse.iitb.ac.in');
$short is of type array and contains following :
$short['status']['code'] :- status code for the operation
$short['status']['text'] :- status text for the operation
$short['short_url'] :- shortened URL for 'www.cse.iitb.ac.in'
$short['long_url'] :- 'www.cse.iitb.ac.in'
$short['global_hash'] :- global hash value for the URL. This is other shortened URL :- 'bit.ly/' + global_hash

  • Expand a bit.ly URL :
$expand = $bit->expandURL('http://bit.ly/9Ty5JM');
$expand is same as $short.

  • Validate a user :
$valid = $bit->validate(login, apikey);
$valid is of type array and contains following :
It contains same status messages as $short
$valid['valid'] :- returns 1 if (login, apikey) is valid else 0

  • Set new user and api key
$bit->setLoginAndKey(login, key);
This changes the login name and the api key.