ZendFramework example on using Google URL Shortener service

Seems like URL shorteners have gain extreme popularity with web services like Twitter. Not to mention the fact that long URLs are somewhat hard to pass along. They are also harder to verbalize in a conversation, and above all in some cases they are almost impossible to remember.

There are quite a large number of URL shorteners out there these days, mostly free. One of the freshest is Google’s URL shortener. This article is not about outlining the features that make this shortener better then the other ones (as I am sure some offer more features at the moment). This article is merely for the purpose of showing you how easy it is to use the Google URL Shortener service via your ZendFramework libraries.

Basically all we need is the instance of Zend_Http_Client class and preferably the API key for Google URL Shortener. For API key, just follow the instructions outlined here.

Here are the few actions you can with the Google URL Shortener at the moment:

  • Shorten a long URL
  • Expand a short URL
  • Look up a short URL’s analytics
  • Look up a user’s history

Example #1 – Shorten a long URL

$client = new Zend_Http_Client();
 
$client->setUri('https://www.googleapis.com/urlshortener/v1/url');
$client->setHeaders(Zend_Http_Client::CONTENT_TYPE, 'application/json');
$client->setMethod(Zend_Http_Client::POST);
 
$payload = json_encode(array(
    'longUrl' => 'http://activecodeline.net/',
    'key' => '___YOUR_API_KEY_HERE___'
));
 
$client->setRawData($payload);
 
$response = $client->request();

Below you can see the example of response for the above request.

Zend_Debug::dump($response, '$response');
 
/**
$response object(Zend_Http_Response)#225 (5) {
  ["version":protected] => string(3) "1.1"
  ["code":protected] => int(200)
  ["message":protected] => string(2) "OK"
  ["headers":protected] => array(11) {
    ["Cache-control"] => string(46) "no-cache, no-store, max-age=0, must-revalidate"
    ["Pragma"] => string(8) "no-cache"
    ["Expires"] => string(29) "Fri, 01 Jan 1990 00:00:00 GMT"
    ["Date"] => string(29) "Sat, 26 Feb 2011 08:06:45 GMT"
    ["Content-type"] => string(31) "application/json; charset=UTF-8"
    ["X-content-type-options"] => string(7) "nosniff"
    ["X-frame-options"] => string(10) "SAMEORIGIN"
    ["X-xss-protection"] => string(13) "1; mode=block"
    ["Server"] => string(3) "GSE"
    ["Connection"] => string(5) "close"
  }
  ["body":protected] => string(104) "{
 "kind": "urlshortener#url",
 "id": "http://goo.gl/7rDDa",
 "longUrl": "http://activecodeline.net/"
}
"
}
 
*/

Example #2 – Expand a short URL

$client = new Zend_Http_Client();
 
$client->setUri('https://www.googleapis.com/urlshortener/v1/url');
$client->setMethod(Zend_Http_Client::GET);
$client->setParameterGet('shortUrl', 'http://goo.gl/7rDDa');
$client->setParameterGet('key', '___YOUR_API_KEY_HERE___');
 
$client->setRawData($payload);
 
$response = $client->request();

Below you can see the example of response for the above request.

Zend_Debug::dump($response, '$response');
 
/**
 
$response object(Zend_Http_Response)#225 (5) {
  ["version":protected] => string(3) "1.1"
  ["code":protected] => int(200)
  ["message":protected] => string(2) "OK"
  ["headers":protected] => array(11) {
    ["Expires"] => string(29) "Sat, 26 Feb 2011 08:37:13 GMT"
    ["Date"] => string(29) "Sat, 26 Feb 2011 08:32:13 GMT"
    ["Content-type"] => string(31) "application/json; charset=UTF-8"
    ["X-content-type-options"] => string(7) "nosniff"
    ["X-frame-options"] => string(10) "SAMEORIGIN"
    ["X-xss-protection"] => string(13) "1; mode=block"
    ["Server"] => string(3) "GSE"
    ["Cache-control"] => string(50) "public, max-age=300, must-revalidate, no-transform"
    ["Age"] => string(2) "48"
    ["Connection"] => string(5) "close"
  }
  ["body":protected] => string(121) "{
 "kind": "urlshortener#url",
 "id": "http://goo.gl/7rDDa",
 "longUrl": "http://activecodeline.net/",
 "status": "OK"
}
"
}
 
*/

Example #3 – Look up a short URL’s analytics

$client = new Zend_Http_Client();
 
$client->setUri('https://www.googleapis.com/urlshortener/v1/url');
$client->setMethod(Zend_Http_Client::GET);
$client->setParameterGet('shortUrl', 'http://goo.gl/7rDDa');
$client->setParameterGet('projection', 'FULL');
$client->setParameterGet('key', '___YOUR_API_KEY_HERE___');
 
$client->setRawData($payload);
 
$response = $client->request();

Below you can see the example of response for the above request.

Zend_Debug::dump($response, '$response');
 
/**
 
$response object(Zend_Http_Response)#225 (5) {
  ["version":protected] => string(3) "1.1"
  ["code":protected] => int(200)
  ["message":protected] => string(2) "OK"
  ["headers":protected] => array(10) {
    ["Expires"] => string(29) "Sat, 26 Feb 2011 08:36:40 GMT"
    ["Date"] => string(29) "Sat, 26 Feb 2011 08:36:40 GMT"
    ["Cache-control"] => string(48) "public, max-age=0, must-revalidate, no-transform"
    ["Content-type"] => string(31) "application/json; charset=UTF-8"
    ["X-content-type-options"] => string(7) "nosniff"
    ["X-frame-options"] => string(10) "SAMEORIGIN"
    ["X-xss-protection"] => string(13) "1; mode=block"
    ["Server"] => string(3) "GSE"
    ["Connection"] => string(5) "close"
  }
  ["body":protected] => string(2042) "{
 "kind": "urlshortener#url",
 "id": "http://goo.gl/7rDDa",
 "longUrl": "http://activecodeline.net/",
 "status": "OK",
 "created": "2011-02-26T08:06:45.845+00:00",
 "analytics": {
  "allTime": {
   "shortUrlClicks": "1",
   "longUrlClicks": "1",
   "referrers": [
    {
     "count": "1",
     "id": "Unknown/empty"
    }
   ],
   "countries": [
    {
     "count": "1",
     "id": "HR"
    }
   ],
   "browsers": [
    {
     "count": "1",
     "id": "Chrome"
    }
   ],
   "platforms": [
    {
     "count": "1",
     "id": "Windows"
    }
   ]
  },
  "month": {
   "shortUrlClicks": "1",
   "longUrlClicks": "1",
   "referrers": [
    {
     "count": "1",
     "id": "Unknown/empty"
    }
   ],
   "countries": [
    {
     "count": "1",
     "id": "HR"
    }
   ],
   "browsers": [
    {
     "count": "1",
     "id": "Chrome"
    }
   ],
   "platforms": [
    {
     "count": "1",
     "id": "Windows"
    }
   ]
  },
  "week": {
   "shortUrlClicks": "1",
   "longUrlClicks": "1",
   "referrers": [
    {
     "count": "1",
     "id": "Unknown/empty"
    }
   ],
   "countries": [
    {
     "count": "1",
     "id": "HR"
    }
   ],
   "browsers": [
    {
     "count": "1",
     "id": "Chrome"
    }
   ],
   "platforms": [
    {
     "count": "1",
     "id": "Windows"
    }
   ]
  },
  "day": {
   "shortUrlClicks": "1",
   "longUrlClicks": "1",
   "referrers": [
    {
     "count": "1",
     "id": "Unknown/empty"
    }
   ],
   "countries": [
    {
     "count": "1",
     "id": "HR"
    }
   ],
   "browsers": [
    {
     "count": "1",
     "id": "Chrome"
    }
   ],
   "platforms": [
    {
     "count": "1",
     "id": "Windows"
    }
   ]
  },
  "twoHours": {
   "shortUrlClicks": "1",
   "longUrlClicks": "1",
   "referrers": [
    {
     "count": "1",
     "id": "Unknown/empty"
    }
   ],
   "countries": [
    {
     "count": "1",
     "id": "HR"
    }
   ],
   "browsers": [
    {
     "count": "1",
     "id": "Chrome"
    }
   ],
   "platforms": [
    {
     "count": "1",
     "id": "Windows"
    }
   ]
  }
 }
}
"
}
 
*/

The above 3 examples are pretty easy, and straight forward. Last example, “Look up a user’s history”, requires a bit more finesse as it requires your/user authentication in order to get the proper response. There are several ways you can authenticate (OAuth, ClientLogin). OAuth is the preferred mechanism for logging in and performing actions on behalf of a Google user.

If Oauth is not feasible, you can use ClientLogin. With this mechanism, you give google.com an email and password in exchange for an access token.

In this last example “Look up a user’s history” I will show you how to do it with ClientLogin approach as it is somewhat simpler. However, this does not mean that ClientLogin approach will suite your needs, in which case you should really study the Oauth implementation.

Example #4 – Look up a user’s history

$clientLogin = new Zend_Http_Client();
 
$clientLogin->setUri('https://www.google.com/accounts/ClientLogin');
$clientLogin->setMethod(Zend_Http_Client::POST);
$clientLogin->setHeaders(Zend_Http_Client::CONTENT_TYPE, 'application/x-www-form-urlencoded');
$clientLogin->setParameterPost('accountType', 'HOSTED_OR_GOOGLE');
$clientLogin->setParameterPost('Email', '_YOUR_GOOGLE_EMAIL_HERE_');
$clientLogin->setParameterPost('Passwd', '_YOUR_GOOGLE_PASS_HERE_');
$clientLogin->setParameterPost('service', 'urlshortener');
$clientLogin->setParameterPost('source', 'myname-testapp-1.0.1');
 
$responseLogin = $clientLogin->request();
$responseLoginBody = $responseLogin->getBody();
 
$loginTokens = explode("\n", $responseLoginBody);
$authToken = '';
 
foreach ($loginTokens as $r) {
    $_r = explode("=", $r);
    if (count($_r) > 1) {
        if ($_r[0] == 'Auth') {
            $authToken = $_r[1];
        }
    }
}
 
if (!empty($authToken)) {
    $clientHistory = new Zend_Http_Client();
 
    $clientHistory->setUri('https://www.googleapis.com/urlshortener/v1/url/history');
    $clientHistory->setMethod(Zend_Http_Client::GET);
    $clientHistory->setHeaders(Zend_Http_Client::CONTENT_TYPE, 'application/json');
    $clientHistory->setHeaders('Authorization', 'GoogleLogin auth='.$authToken);
    $clientHistory->setParameterGet('key', '___YOUR_API_KEY_HERE___');
 
    $responseHistory = $clientHistory->request();
    $responseHistoryBody = $responseHistory->getBody();
    //Zend_Debug::dump($responseHistoryBody, '$responseHistoryBody');
    //Zend_Debug::dump($responseHistory, '$responseHistory');
}

Below you can see the example of response for the above request.

Zend_Debug::dump($responseHistory, '$responseHistory');
 
/**
 
$responseHistory object(Zend_Http_Response)#237 (5) {
  ["version":protected] => string(3) "1.1"
  ["code":protected] => int(200)
  ["message":protected] => string(2) "OK"
  ["headers":protected] => array(10) {
    ["Expires"] => string(29) "Sat, 26 Feb 2011 10:20:34 GMT"
    ["Date"] => string(29) "Sat, 26 Feb 2011 10:20:34 GMT"
    ["Cache-control"] => string(49) "private, max-age=0, must-revalidate, no-transform"
    ["Content-type"] => string(31) "application/json; charset=UTF-8"
    ["X-content-type-options"] => string(7) "nosniff"
    ["X-frame-options"] => string(10) "SAMEORIGIN"
    ["X-xss-protection"] => string(13) "1; mode=block"
    ["Server"] => string(3) "GSE"
    ["Connection"] => string(5) "close"
  }
  ["body":protected] => string(2943) "{
 "kind": "urlshortener#urlHistory",
 "totalItems": 13,
 "itemsPerPage": 30,
 "items": [
  {
   "kind": "urlshortener#url",
   "id": "http://goo.gl/IkFNS",
   "longUrl": "http://www.jetbrains.com/phpstorm/whatsnew/index.html",
   "status": "OK",
   "created": "2011-02-25T09:29:03.995+00:00"
  },
  {
   "kind": "urlshortener#url",
   "id": "http://goo.gl/NpdS9",
   "longUrl": "http://www.eclipse.org/egit/?gclid\u003dCPfd-5L_oqcCFZMK3wodkC6_BA",
   "status": "OK",
   "created": "2011-02-25T09:28:28.545+00:00"
  },
  {
   "kind": "urlshortener#url",
   "id": "http://goo.gl/RiVJH",
   "longUrl": "http://www.flickr.com/photos/ajzele/sets/72157626133406912/detail/",
   "status": "OK",
   "created": "2011-02-25T08:46:47.203+00:00"
  },
 
*/

That’s it. Examples above cover the most of what you can do with the Google URL Shortener API at the moment. Hope you find the article useful.


3 comments

  1. Hi,
    Thanks for the post. I just used it with my zend project to shorten several urls for sms, and it worked like a charm. I appreciate your post. Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.