PHP: Google URL Shortener (With Authorization Key): analytics

Google provides URL shortening service goo.gl along with an API. In one of our previous post, we discussed how to make anonymous calls to the service, especailly for shortening, expanding and analytics. But anonymous calls has certain limits, you can not make a large number of calls in a single day. So you can make use of the authorization key. If you haven’t got one, get one from here.

Let’s see the program for URL expansion.

Note that you must substitute YOUR_KEY_HERE with your own authorization key

<?php

/*Base URL of the Service*/
$BASEURL = "https://www.googleapis.com/urlshortener/";

/*Version of the service*/
$VERSION = "v1";

/*Service*/
$SERVICE = "url";

/*Type of the content, e.g. text/xml, application/json*/
$CONTENT_TYPE = "Content-Type: application/json";

/*API name*/
$REQUEST = "shortUrl";

/*Authorization key*/
$KEY='YOUR_KEY_HERE';

function printDetails($hash) {
    foreach($hash as $key => $value){
        if (is_array($value)) {
            print "$key:n";
            foreach($value as $val) {
                if(is_object($val) || is_array($val)){
                     printDetails($val);
                }
                else{
                     print "$val,";
                }
            }
            print "n";
        }
        else if (!is_object($value)) {
            print "$key: $valuen";
        }
        else {
            print "$key:n";
            printDetails($value);
        }
    }
}

function get_response($URL, $type) {

    if(!function_exists('curl_init')) {
    die ("Curl PHP package not installedn");
    }

    /*Initializing CURL*/
    $curlHandle = curl_init();

    /*The URL to be downloaded is set*/
    curl_setopt($curlHandle, CURLOPT_URL, $URL);
    curl_setopt($curlHandle, CURLOPT_HEADER, false);
    curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array($type));
    curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);

    /*Now execute the CURL, download the URL specified*/
    $response = curl_exec($curlHandle);

    /*Return the response as it is, let the application process it accordingly*/
    return $response;
}

/*Specify the url to be expanded*/

if (sizeof($argv) != 2) {
  echo "Usage: $argv[0] urln";
  exit;
}

$url = "$BASEURL$VERSION/$SERVICE";

print "URL: $urln";
print "Analytics of the URL to be found: $argv[1]n";

$response = get_response($url."?key=$KEY&$REQUEST=$argv[1]&projection=FULL", $CONTENT_TYPE);

/*Printing the response on to the console*/
if (isset($response)) {
   $dresponse = json_decode($response);
   if (json_last_error() == JSON_ERROR_NONE){
       if (isset($dresponse->{'longUrl'})) {
           print "======================================================n";
           print "More Details:n";
           print "======================================================n";
           printDetails($dresponse);
           print "======================================================n";
       }
   }
}
else {
   print "Failed to get a responsen";
   exit(1);
}
?>

Let’s execute the program

URL: https://www.googleapis.com/urlshortener/v1/url
Analytics of the URL to be found: http://goo.gl/nhfUT
======================================================
More Details:
======================================================
kind: urlshortener#url
id: http://goo.gl/nhfUT
longUrl: http://example.com/
status: OK
created: 2011-01-11T17:04:27.649+00:00
analytics:
allTime:
shortUrlClicks: 3
longUrlClicks: 3
referrers:
count: 3
id: Unknown/empty

countries:
count: 3
id: IN

browsers:
count: 2
id: Firefox-4.0
count: 1
id: Firefox

platforms:
count: 2
id: Other Unix
count: 1
id: Macintosh

month:
shortUrlClicks: 3
longUrlClicks: 3
referrers:
count: 3
id: Unknown/empty

countries:
count: 3
id: IN

browsers:
count: 2
id: Firefox-4.0
count: 1
id: Firefox

platforms:
count: 2
id: Other Unix
count: 1
id: Macintosh

week:
shortUrlClicks: 3
longUrlClicks: 3
referrers:
count: 3
id: Unknown/empty

countries:
count: 3
id: IN

browsers:
count: 2
id: Firefox-4.0
count: 1
id: Firefox

platforms:
count: 2
id: Other Unix
count: 1
id: Macintosh

day:
shortUrlClicks: 2
longUrlClicks: 2
referrers:
count: 2
id: Unknown/empty

countries:
count: 2
id: ABC

browsers:
count: 2
id: Firefox-4.0

platforms:
count: 2
id: Other Unix

twoHours:
shortUrlClicks: 2
longUrlClicks: 2
referrers:
count: 2
id: Unknown/empty

countries:
count: 2
id: ABC

browsers:
count: 2
id: Firefox-4.0

platforms:
count: 2
id: Other Unix

======================================================
Advertisements

PHP: Google URL Shortener (With Authorization Key): expand

Google provides URL shortening service goo.gl along with an API. In one of our previous post, we discussed how to make anonymous calls to the service, especailly for shortening and expanding. But anonymous calls has certain limits, you can not make a large number of calls in a single day. So you can make use of the authorization key. If you haven’t got one, get one from here.

Let’s see the program for URL expansion.

Note that you must substitute YOUR_KEY_HERE with your own authorization key

<?php

/*Base URL of the Service*/
$BASEURL = "https://www.googleapis.com/urlshortener/";

/*Version of the service*/
$VERSION = "v1";

/*Service*/
$SERVICE = "url";

/*Type of the content, e.g. text/xml, application/json*/
$CONTENT_TYPE = "Content-Type: application/json";

/*API name*/
$REQUEST = "shortUrl";

/*Authorization key*/
$KEY='YOUR_KEY_HERE';

function printDetails($hash) {
    foreach($hash as $key => $value){
        if (is_array($value)) {
            print "$key:n";
            foreach($value as $val) {
                if(is_object($val) || is_array($val)){
                     printDetails($val);
                }
                else{
                     print "$val,";
                }
            }
            print "n";
        }
        else if (!is_object($value)) {
            print "$key: $valuen";
        }
        else {
            print "$key:n";
            printDetails($value);
        }
    }
}

function get_response($URL, $type) {

    if(!function_exists('curl_init')) {
    die ("Curl PHP package not installedn");
    }

    /*Initializing CURL*/
    $curlHandle = curl_init();

    /*The URL to be downloaded is set*/
    curl_setopt($curlHandle, CURLOPT_URL, $URL);
    curl_setopt($curlHandle, CURLOPT_HEADER, false);
    curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array($type));
    curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);

    /*Now execute the CURL, download the URL specified*/
    $response = curl_exec($curlHandle);

    /*Return the response as it is, let the application process it accordingly*/
    return $response;
}

/*Specify the url to be expanded*/

if (sizeof($argv) != 2) {
  echo "Usage: $argv[0] urln";
  exit;
}

$url = "$BASEURL$VERSION/$SERVICE";

print "URL: $urln";
print "URL To be expanded: $argv[1]n";

$response = get_response($url."?key=$KEY&$REQUEST=$argv[1]", $CONTENT_TYPE);

/*Printing the response on to the console*/
if (isset($response)) {
   $dresponse = json_decode($response);
   if (json_last_error() == JSON_ERROR_NONE){
       if (isset($dresponse->{'longUrl'})) {
           print "The Expanded URL is: ". $dresponse->{'longUrl'}."n";
           print "======================================================n";
           print "More Details:n";
           print "======================================================n";
           printDetails($dresponse);
           print "======================================================n";
       }
   }
}
else {
   print "Failed to get a responsen";
   exit(1);
}
?>

Let’s execute the program

$ php expand.php http://goo.gl/nhfUT

URL: https://www.googleapis.com/urlshortener/v1/url
URL To be expanded: http://goo.gl/nhfUT
The Expanded URL is: http://example.com/
======================================================
More Details:
======================================================
kind: urlshortener#url
id: http://goo.gl/nhfUT
longUrl: http://example.com/
status: OK
======================================================

PHP: Google URL Shortener (With Authorization Key): shorten

Google provides URL shortening service goo.gl along with an API. In one of our previous post, we discussed how to make anonymous calls to the service, especailly for shortening. But anonymous calls has certain limits, you can not make a large number of calls in a single day. So you can make use of the authorization key. If you haven’t got one, get one from here.

Let’s see the program for URL shortening.

Note that you must substitute YOUR_KEY_HERE with your own authorization key

<?php

/*Base URL of the Service*/
$BASEURL = "https://www.googleapis.com/urlshortener/";

/*Version of the service*/
$VERSION = "v1";

/*Service*/
$SERVICE = "url";

/*Type of the content, e.g. text/xml, application/json*/
$CONTENT_TYPE = "Content-Type: application/json";

/*API name*/
$REQUEST = "longUrl";

/*Authorization key*/
$KEY='YOUR_KEY_HERE';

function printDetails($hash) {
    foreach($hash as $key => $value){
        if (is_array($value)) {
            print "$key:n";
            foreach($value as $val) {
                if(is_object($val) || is_array($val)){
                     printDetails($val);
                }
                else{
                     print "$val,";
                }
            }
            print "n";
        }
        else if (!is_object($value)) {
            print "$key: $valuen";
        }
        else {
            print "$key:n";
            printDetails($value);
        }
    }
}

function get_response($URL, $type, $content) {

    if(!function_exists('curl_init')) {
    die ("Curl PHP package not installedn");
    }

    /*Initializing CURL*/
    $curlHandle = curl_init();

    /*The URL to be downloaded is set*/
    curl_setopt($curlHandle, CURLOPT_URL, $URL);
    curl_setopt($curlHandle, CURLOPT_HEADER, false);
    curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array($type));
    curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $content);
    curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);

    /*Now execute the CURL, download the URL specified*/
    $response = curl_exec($curlHandle);

    /*Return the response as it is, let the application process it accordingly*/
    return $response;
}

/*Specify the url to be shortened*/

if (sizeof($argv) != 2) {
  echo "Usage: $argv[0] urln";
  exit;
}

$url = "$BASEURL$VERSION/$SERVICE";

print "URL: $urln";
print "URL To be shortened: $argv[1]n";

/*Create the Request*/
$request = array($REQUEST => $argv[1]);

/*Encode the request as a json object*/
$jsonrequest = json_encode($request);

$response = get_response($url."?key=$KEY", $CONTENT_TYPE, $jsonrequest);

/*Printing the response on to the console*/
if (isset($response)) {
   $dresponse = json_decode($response);
   if (json_last_error() == JSON_ERROR_NONE){
       if (isset($dresponse->{'id'})) {
           print "The Shortened URL is: ". $dresponse->{'id'}."n";
           print "======================================================n";
           print "More Details:n";
           print "======================================================n";
           printDetails($dresponse);
           print "======================================================n";
       }
   }
}
else {
   print "Failed to get a responsen";
   exit(1);
}
?>

Let’s now execute the program

$php shorten.php http://example.com

URL: https://www.googleapis.com/urlshortener/v1/url
URL To be shortened: http://example.com
The Shortened URL is: http://goo.gl/nhfUT
======================================================
More Details:
======================================================
kind: urlshortener#url
id: http://goo.gl/nhfUT
longUrl: http://example.com/
======================================================

PHP: Google URL Shortener: expand

Now since you have been able to successfully shorten an URL, it’s time to see how to expand a shortened URL. The following program shows how to expands a shortened URL without making use of a key.

<?php

/*Base URL of the Service*/
$BASEURL = "https://www.googleapis.com/urlshortener/";

/*Version of the service*/
$VERSION = "v1";

/*Service*/
$SERVICE = "url";

/*Type of the content, e.g. text/xml, application/json*/
$CONTENT_TYPE = "Content-Type: application/json";

/*API name*/
$REQUEST = "shortUrl";

function printDetails($hash) {
    foreach($hash as $key => $value){
        if (is_array($value)) {
            print "$key:n";
            foreach($value as $val) {
                if(is_object($val) || is_array($val)){
                     printDetails($val);
                }
                else{
                     print "$val,";
                }
            }
            print "n";
        }
        else if (!is_object($value)) {
            print "$key: $valuen";
        }
        else {
            print "$key:n";
            printDetails($value);
        }
    }
}

function get_response($URL, $type) {

    if(!function_exists('curl_init')) {
    die ("Curl PHP package not installedn");
    }

    /*Initializing CURL*/
    $curlHandle = curl_init();

    /*The URL to be downloaded is set*/
    curl_setopt($curlHandle, CURLOPT_URL, $URL);
    curl_setopt($curlHandle, CURLOPT_HEADER, false);
    curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array($type));
    curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);

    /*Now execute the CURL, download the URL specified*/
    $response = curl_exec($curlHandle);

    /*Return the response as it is, let the application process it accordingly*/
    return $response;
}

/*Specify the url to be expanded*/

if (sizeof($argv) != 2) {
  echo "Usage: $argv[0] urln";
  exit;
}

$url = "$BASEURL$VERSION/$SERVICE";

print "URL: $urln";
print "URL To be expanded: $argv[1]n";

$response = get_response($url."?$REQUEST=$argv[1]", $CONTENT_TYPE);

/*Printing the response on to the console*/
if (isset($response)) {
   $dresponse = json_decode($response);
   if (json_last_error() == JSON_ERROR_NONE){
       if (isset($dresponse->{'longUrl'})) {
           print "The Expanded URL is: ". $dresponse->{'longUrl'}."n";
           print "======================================================n";
           print "More Details:n";
           print "======================================================n";
           printDetails($dresponse);
           print "======================================================n";
       }
   }
}
else {
   print "Failed to get a responsen";
   exit(1);
}
?>

Let’s execute the above program with a shortened URL

$ php expand.php http://goo.gl/nhfUT

URL: https://www.googleapis.com/urlshortener/v1/url
URL To be expanded: http://goo.gl/nhfUT
The Expanded URL is: http://example.com/
======================================================
More Details:
======================================================
kind: urlshortener#url
id: http://goo.gl/nhfUT
longUrl: http://example.com/
status: OK
======================================================

PHP: Google URL Shortener API Tutorial with Examples

Google has released the Google URL Shortener API. This means that you can make use of this service in your websites, clients and programs. What this means to the developer is that he can access the Google URL shortener service through REST calls in his programs.

The API is released as a web service. The API can be accessed using REST calls. There are mainly three functions

  1. Shorten: Used to shorten a long URL
  2. Expand: Used to expand a shortener URL
  3. Analytics: Get the details of the shortened URL like how many people clicked the shortened URL and from where

There are two ways by which you can access the service

  1. With Key
  2. Without Key

If you have a key, you can be able to make a large number of URL shortener calls. You can also perform without the key. This tutorail explains both the methods of accessing the service.

  1. Without Key
    1. Shorten
    2. Expand
    3. Analytics
  2. With Authorization Key
    1. Shorten URL
    2. URL Expansion
    3. Shortened URL Analytics

json_object_new_object: Creating a new Json object

json_object_new_object is used to create a new json object. Once you create a json object, you can add more objects to it.

The syntax of the function is

json_object * json_object_new_object ()

As you can see, it returns a pointer to the json object

The following program shows the usage of the function


#include <json/json.h>
#include <stdio.h>

int main() {
  /*Creating a json object*/
  json_object * jobj = json_object_new_object();

  /*Creating a json string*/
  json_object *jstring = json_object_new_string("Joys of Programming");

  /*Creating a json integer*/
  json_object *jint = json_object_new_int(10);

  /*Creating a json boolean*/
  json_object *jboolean = json_object_new_boolean(1);

  /*Creating a json double*/
  json_object *jdouble = json_object_new_double(2.14);

  /*Creating a json array*/
  json_object *jarray = json_object_new_array();

  /*Creating json strings*/
  json_object *jstring1 = json_object_new_string("c");
  json_object *jstring2 = json_object_new_string("c++");
  json_object *jstring3 = json_object_new_string("php");

  /*Adding the above created json strings to the array*/
  json_object_array_add(jarray,jstring1);
  json_object_array_add(jarray,jstring2);
  json_object_array_add(jarray,jstring3);

  /*Form the json object*/
  /*Each of these is like a key value pair*/
  json_object_object_add(jobj,"Site Name", jstring);
  json_object_object_add(jobj,"Technical blog", jboolean);
  json_object_object_add(jobj,"Average posts per day", jdouble);
  json_object_object_add(jobj,"Number of posts", jint);
  json_object_object_add(jobj,"Categories", jarray);

  /*Now printing the json object*/
  printf ("The json object created: %sn",json_object_to_json_string(jobj));

}

The output of the program is something like this

The json object created: { "Site Name": "Joys of Programming", "Technical blog": true, "Average posts per day": 2.140000, "Number of posts": 10, "Categories": [ "c", "c++", "php" ] }

The output is something like this

{
    "Site Name": "Joys of Programming",
    "Technical blog": true,
    "Average posts per day": 2.140000,
    "Number of posts": 10,
    "Categories": [
        "c",
        "c++",
        "php" 
    ] 
}

json_object_is_type: Check the type of json object

json_object_is_type is used to check whether the type of the json object is same as that of the specified type. So you can easily guess that the function takes two arguments


#include <json/json.h>
#include <stdio.h>

int main() {
  char * string = "{"sitename" : "joys of programming",
                     "tags" : [ "c" , "c++", "java", "PHP" ],
                     "author-details": { "name" : "Joys of Programming", "Number of Posts" : 10 } 
                     }";
  json_object * jobj = json_tokener_parse(string);
  enum json_type type;
  json_object_object_foreach(jobj, key, val) {
    printf("type: ",type);
    if (json_object_is_type(val, json_type_null)) {
     printf("json_type_nulln");
    }
    if (json_object_is_type(val, json_type_boolean)) {
     printf("json_type_booleann");
    }
    if (json_object_is_type(val, json_type_double)) {
     printf("json_type_doublen");
    }
    if (json_object_is_type(val, json_type_int)) {
     printf("json_type_intn");
    }
    if (json_object_is_type(val, json_type_object)) {
     printf("json_type_objectn");
    }
    if (json_object_is_type(val, json_type_array)) {
     printf("json_type_arrayn");
    }
    if (json_object_is_type(val, json_type_string)) {
     printf("json_type_stringn");
    }
  }
}

The output of the program is something like this

type: json_type_string
type: json_type_array
type: json_type_object

The input to the program is

{
    "sitename" : "joys of programming",
    "tags" : [
        "c" ,
        "c++",
        "java",
        "PHP"
    ],
    "author-details": {
        "name" : "Joys of Programming",
        "Number of Posts" : 10
    }
}