Goo.gl URL Shortener

Here’s a simple class for URL shortening using Google’s new URL API:

<?php

class GUrl {
	$api_url = "https://www.googleapis.com/urlshortener/v1/url?key=";
	$key;
	
	function __construct ($key = "YOUR_API_KEY") {
		// set up the API key if it exists
		$this->key = $key;
	}
	
	public function shortenUrl ($url) {
		curl_init();
		// concatenate the API url
		curl_setopt($ch,CURLOPT_URL,$this->api_url . $this->key);
		curl_setopt($ch,CURLOPT_POST,1);
		// send the json ecoded long version of the url
		curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
		curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		// execute
		$result = curl_exec($ch);
		// close
		curl_close($ch);
		// return the result
		return ($result['id'] = json_decode($result,true)) ? $result['id'] : false;
	}
}

?>

That’s it! Just one function to have cURL send Google the URL to be shortened and it should return a response with the shortened version contained within the parameter [‘id’]. The great thing about using google for this is later we can build a class to retrieve periodic analytics on these urls and see which links are performing well.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.