top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

    Get Free Article Updates

Facebook Login
Site Registration

PHP: URL shortner using

0 votes

Google has had a URL shortening domain for quite a while now. I took a few minutes to review their API and created a very basic function where you pass the URL and the key ( ) and it will do the magic for you.

PHP Function

function get_short_url($key, $url)
        $postData = array('longUrl' => $url, 'key' => $key);
        $jsonData = json_encode($postData);

        $curlObj = curl_init();

        curl_setopt($curlObj, CURLOPT_URL, '');
        curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curlObj, CURLOPT_HEADER, 0);
        curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
        curl_setopt($curlObj, CURLOPT_POST, 1);
        curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);

        $response = curl_exec($curlObj);

        // Change the response json string to object
        $json = json_decode($response, true);


        return isset($json['id']) ? $json['id'] : false;


$key - You API key 
$url - Long URL which needs to be shortened 

Return Parameter:

FALSE - if url is not shortened 
short url - if url is shortened 

Note: This code is a tested code and used to run at QueryHome before we moved to

posted May 21, 2014 by Salil Agrawal

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button

Related Articles

URL shortening is a technique in which url made substantially shorter in length and still direct to the required page. This is achieved by using an HTTP Redirect on a domain name that is short, which links to the web page that has a long URL.

Short URL is convenient for microblogging which has a 140 character limit. Here in this article I am describing url shortner in PHP using

Step 1: get the key and username from (you may require to register) this will provide you the BITLY USERNAME and BITLY API KEY

Step 2: Now from your PHP code you need to pass the key and url which you want to shorten and the username.

function get_short_bitty_url($key, $url, $username)
      $ch = curl_init("$username&apiKey=$key&longUrl=$url");
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

      $result = curl_exec($ch);
      $json = json_decode($result, true);
      return $json['status_code'] == 200 ? $json['data']['url'] : false;

This function will return false if could not shorten the url for some reason else it will return the short url of the passed long url.

Note: This code is running at the QueryHome.

Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.