Shorten URL using Google URL Shortener API


In this tutorial I will show you how you can shorten URL using Google URL Shortener API with PHP. Google provides URL shortener service (goo.gl) with a Google URL Shorten API key.

Get detail information of Google Shortener API from http://code.google.com/apis/urlshortener. Get your API key by creating a project or existing project from https://console.developers.google.com. I have created a basic GoogleShortUrlApi class for shorten long URLs and expand shortened URLs.

class GoogleShortUrlApi {
	private $apiURL = 'https://www.googleapis.com/urlshortener/v1/url';

	function __construct($apiKey) {
		$this->apiURL = $this->apiURL.'?key='.$apiKey;
	}

	// Shorten a URL
	function shorten($url) {
		$data = $this->send($url);
		return isset($data['id']) ? $data['id'] : false;
	}

	// Expand a URL
	function expand($url) {
		$data = $this->send($url,false);
		return isset($data['longUrl']) ? $data['longUrl'] : false;
	}

	// Send information to Google
	function send($url,$shorten = true) {
		$ch = curl_init();
		if($shorten) {
			curl_setopt($ch,CURLOPT_URL, $this->apiURL);
			curl_setopt($ch,CURLOPT_POST,1);
			curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
			curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
		} else {
			curl_setopt($ch,CURLOPT_URL, $this->apiURL.'&shortUrl='.$url);
		}

		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false );
		$result = curl_exec($ch);
		curl_close($ch);
		return json_decode($result, true);
	}
}

This class has 2 basic methods, shorten for Shorten long URL and expand for Expand shorten URL. Class uses CURL to send request to Google and gets results in JSON format. So you can use this class by providing API key as below:

$key = 'AIzaSyBATzOV1YURTG334IqowoHFqGIB0zubbs';
$api = new GoogleShortUrlApi($key);

// Shorten a URL
$shortURL = $api->shorten("www.tricksofit.com");
echo "Short URL : ".$shortURL; // Short URL : http://goo.gl/G4OuoF

echo "<br>";
// Expand a URL
$longURL = $api->expand($shortURL);
echo "Long URL : ".$longURL;  // Long URL : http://www.tricksofit.com/

Hope This tutorial will help you to Shorten URL using Google URL Shortener API with PHP.