Skip to Content

A PHP class for Bit.ly

Bit.ly is a very popular service that shortens long url's to something much shorter, eg. http://bit.ly/aclhAK. This is invaluable for use with Twitter because the character limit precludes the use of normal 'long' urls.

The PHP class below can be used to connect to the Bit.ly API and generate short urls' for your software projects. To use it, first signup for an api key at Bit.ly, then copy the class into your project.


class bitly {
    
    var $username;         // bitly username
    var $key;                   // bitly key
    var $bitly_url;            // bitly_url
    var $query_url;         // bitly url query string
    var $curl_channel;
    
    function __construct($options) {
        // constructor
        $this->username = $options['username'];
        $this->key = $options['bitly_key'];
        $this->bitly_url = $options['bitly_url'];
    }
    
    function make_short_url($url) {
        // makes a short url
        // specify correct connection type
        $this->query_url = $this->bitly_url."/v3/shorten?login=". 
              $this->username."&apiKey=". $this->key. 
              "&uri=". urlencode($url). "&format=json";
        // make a curl connection using the above url
        $this->make_connection();
        // connect to bitly and get result
        $json_result = $this->send_page();
        // decode json output
        $result = json_decode($json_result, true);
        if ($result['status_code'] == "200") {
            // connection successful
            if (isset($result['data']['url']) && $result['data']['url']) {
                // we have a valid short url from bitly
                return $result['data']['url'];
            } 
            else return 0;  
        }
        else return 0;
    }
    
    function send_page() {
        if ($this->curl_channel) {
            $result = curl_exec($this->curl_channel);
            curl_close($this->curl_channel);
            return $result;
        }
    }
    function make_connection() {
        // creates a curl channel using the query string generated above
        $this->curl_channel = curl_init();
        curl_setopt($this->curl_channel , CURLOPT_URL, $this->query_url);
        curl_setopt($this->curl_channel , CURLOPT_CONNECTTIMEOUT, 2);
        curl_setopt($this->curl_channel , CURLOPT_RETURNTRANSFER, 1);
    }
}

Example implementation


// set the options for the class
$options = array(
    'username' => 'your_bitly_username_here',
    'bitly_key' => 'your_bitly_key_here',
    'bitly_url' => 'http://api.bit.ly'
);

// make the new object
$bitly = new bitly($options);

// call the short_url method
echo $bitly->make_short_url('your_url_to_make_shorter');

DId you like this?

If you liked this, why not make a donation and help support ongoing development.

Comments