Tuesday, June 25, 2013

URL shortner using Bitly - PHP

For creating a shorten url you need to create an account in the following link:

http://dev.bitly.com/my_apps.html

Now go to 

https://bitly.com/a/oauth_apps 

Here you need to create a accesstoken if you are creating for the first time it prompts for the password.

Then you get a alpha numeric value as accesstoken section.


Now use the following Code:

    $url = "https://api-ssl.bitly.com/v3/shorten";
    $strPost = "longUrl=http%3A%2F%2Fgoogle.com%2F&   access_token=YOUR ACCESSTOKEN";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    // curl_setopt($ch, CURLOPT_PROXY, $proxy);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_HTTPGET,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: application/json"));
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $strPost); // add POST fields
    curl_setopt($ch, CURLOPT_POST, 1);
    $result = curl_exec($ch);
    var_dump($result);
    curl_close($ch);


The output of this file will return a json string
 
{
    "status_code" : 200,
    "status_txt" : "OK",
    "data" : {
        "long_url" : "http:\/\/google.com\/",
        "url" : "http:\/\/bit.ly\/14UO8lv",
        "hash" : "14UO8lv",
        "global_hash" : "900913",
        "new_hash" : 1
    }
}



NOTE
The bitly code is to be used for personal accounts cannot be used for Enterprise use if you want to use it for Enterprise you need to request them for the details but this code even works for that Code too.