Google URL Shortening Service PHP Script
Google’s URL Shortener has been used by Google services like FeedBurner, Google News, Blogger to share links on Twitter. Google didn’t provide a web interface for the service, but third-party sites managed to fill the void.
Now you can go to goo.gl, paste any web address and get a short URL. Google also shows stats for any short URL generated using the service: append “.info” to the address and you’ll see the number of clicks, a list of traffic sources and some aggregate information about visitors.
So where do you start? well if you don’t have a google account signup now and then get an API Key.
If you sign in to a Google account, Google will save a list of recently generated URLs. Another advantage is that Google will always generate unique URLs when you are logged in, so that the stats are more useful.
Now that you have your google account and API Key we need to create some PHP code that will grab our short url and display it. First, I’ll walk you through on how it’s done, then I’ll give the full script at the end. Let’s start off with what we need, and that is, the URL that you want to shorten.
$url = 'http://benzingtech.com/fort-myers-web-design/';
If you want to associate the shortened urls to your Google account, just put it your email address and password. You can also add in a Google API key if you have one. Remember, these values are optional.
$email = ''; // OPTIONAL: GMail or Google Apps email address $password = ''; // OPTIONAL: Your Password for above account $api_key = ''; // Required
Next thing we do is use Google’s ClientLogin API to get an Auth key for us to authenticate our requests later. Notice the POST parameters that we include in the request, as required by the API. See the ClientLogin documentation to view other details. For this example I used the Sudocode xhttp class to fetch my results.
if($email and $password) { $data = array(); $data['post'] = array( 'accountType' => 'HOSTED_OR_GOOGLE', 'Email' => $email, 'Passwd' => $password, 'service' => 'urlshortener', 'source' => 'benzingtech-example-v1' // Application's name, e.g. companyName-applicationName-versionID ); $response = xhttp::fetch('https://www.google.com/accounts/ClientLogin', $data);
One IMPORTANT note is the service parameter, “urlshortener”, which is undocumented.
If the request was successful, it will return three lines of text; one for each key: SID, LSID and Auth.
SID=DQAAAGgA...7Zg8CTN LSID=DQAAAGsA...lk8BBbG Auth=DQAAAGgA...dk3fA5N
The lines are way much longer than the example above. If not successful, refer to the documention for the error codes you might get when trying to login. We just need the Auth key for our script and we use PHP’s function preg_match to extract it.
preg_match('/Auth=(.+)/', $response['body'], $matches); $auth = $matches[1];
Here is why I said earlier that I don’t advise using the code as-is, the Auth key can be cached for a long time, as long as you use it regularly. Be sure to cache your Auth Key between sequential requests to minimize URL fetches thus making your app faster and use less processes.
Now that we got our Auth key, and URL to shorten finally, we ask goo.gl to shorten our long URL. We pass off the Auth key in the Authorization header.
if(isset($auth)) $data['headers']['Authorization'] = "GoogleLogin auth=$auth"; if($api_key) $data['get']['key'] = $api_key;
We set the correct Content-Type (application/json), as expected by the API. My xhttp class takes care of converting the array to a JSON string.
$data['headers']['Content-Type'] = "application/json"; $data['post'] = array( 'longUrl' => $url, ); $response = xhttp::fetch("https://www.googleapis.com/urlshortener/v1/url", $data);
Congrats you are Done. We could retrieve the short url by decoding the response and getting the id field like so:
$var = json_decode($response['body'], true); $shortURL = $var['id']; echo $shortURL;
Note: that a new URL is generated for each request even if you shorten the same long URL if you do not use the API Key
<?php $url = 'http://benzingtech.com/fort-myers-web-design/'; $email = ''; // OPTIONAL: GMail or Google Apps email address $password = ''; // OPTIONAL: Your Password for above account $api_key = ''; // Required require 'class.xhttp.php'; if($email and $password) { $data = array(); $data['post'] = array( 'accountType' => 'HOSTED_OR_GOOGLE', 'Email' => $email, 'Passwd' => $password, 'service' => 'urlshortener', 'source' => 'benzingtech-example-v1' // Application's name, e.g. companyName-applicationName-versionID ); $response = xhttp::fetch('https://www.google.com/accounts/ClientLogin', $data); // Check if login failed if(!$response['successful']) { echo "Login Failed\n"; print_r($response); die(); } preg_match('/Auth=(.+)/', $response['body'], $matches); $auth = $matches[1]; } $data = array(); if(isset($auth)) $data['headers']['Authorization'] = "GoogleLogin auth=$auth"; if($api_key) $data['get']['key'] = $api_key; $data['headers']['Content-Type'] = "application/json"; $data['post'] = array( 'longUrl' => $url, ); $response = xhttp::fetch("https://www.googleapis.com/urlshortener/v1/url", $data); if($response['successful']) { $var = json_decode($response['body'], true); $shortURL = $var['id']; echo $shortURL; } else { print_r($response); } ?>