top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

PHP: URL shortner using goo.gl

0 votes
1,355 views

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 (http://code.google.com/apis/urlshortener/ ) 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, 'https://www.googleapis.com/urlshortener/v1/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);

        curl_close($curlObj);

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

Parameters:

$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 bit.ly

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 bit.ly

Step 1: get the key and username from http://bitly.com/a/your_api_key (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("http://api.bitly.com/v3/shorten?login=$username&apiKey=$key&longUrl=$url");
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

This function will return false if bit.ly 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.

READ MORE
...