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/
======================================================

How to get HTTP headers from CURL response?

You can write a simple PHP curl program to download a page. Every HTTP response contains a Header and the contents. In most cases, you will be concerned more about the contents. By default, curl response will give you the contents. But you can also specify that you need the header using the option CURLOPT_HEADER in your program with the curl_setopt function

curl_setopt($curlHandle, CURLOPT_HEADER, true);

Let’s see the complete program which is also give here.

<?php

function downloadURL($URL) {
 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);
 /*Return the HTTP headers*/
 curl_setopt($curlHandle, CURLOPT_HEADER, true);
 /*Now execute the CURL, download the URL specified*/
 $response = curl_exec($curlHandle);
 return $response;
}

echo downloadURL("http://www.mozilla.org/");
?>

Let’s execute the program

$ php download.php | less

The output of the program will be something like this

HTTP/1.1 200 OK
Server: Apache
X-Backend-Server: pp-web03
Vary: Accept-Encoding
Content-Type: text/html; charset=UTF-8
Date: Fri, 06 Aug 2010 15:32:00 GMT
Expires: Fri, 06 Aug 2010 01:42:00 GMT
Transfer-Encoding: chunked
X-Powered-By: PHP/5.2.9
X-Cache-Info: not cacheable; response has already expired

<!DOCTYPE html>
<html lang="en-US" dir="ltr">

As you can see that there is the HTTP header in the top of the response. You can see disabling the CURLOPT_HEADER to false

How to remove HTTP headers from CURL response?

You can write a simple PHP curl program to download a page. Every HTTP response contains a Header and the contents. In most cases, you will be concerned more about the contents. By default, curl response will give you the contents. But you can also specify that you need only the contents and not the header using the option CURLOPT_HEADER in your program with the curl_setopt function

curl_setopt($curlHandle, CURLOPT_HEADER, false);

Let’s see the complete program which is also give here.

<?php

function downloadURL($URL) {
 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);
 /*Don't return the headers*/
 curl_setopt($curlHandle, CURLOPT_HEADER, false);
 /*Now execute the CURL, download the URL specified*/
 $response = curl_exec($curlHandle);
 return $response;
}

echo downloadURL("http://www.mozilla.org/");
?>

Let’s execute the program

$ php download.php | less

The output of the program will be something like this

<!DOCTYPE html>
<html lang="en-US" dir="ltr">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <meta name="DC.description" content="" />
    <meta name="DC.subject" content="" />
    <meta name="DC.creator" content="Happy Cog Studios - http://www.happycog.com" />

If you want to see the difference by enabling CURLOPT_HEADER to true.

Simple PHP Curl Example: Download an URL

To work with websites, both for posting and getting data, CURL is the best option. Curl library is available for almost all languages like C/C++, Java, PHP. To start working with curl, you must install php-curl

Once installed, you can take a look at this simple example.


<?php

function downloadURL($URL) {
 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);

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

echo downloadURL("http://www.mozilla.org/");
?>

Specify any parameter (URL of a webpage) for the function downloadURL. See the output of the script on the browser or the console. You can see the HTML source code of the webpage