URL Shortener

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


class GUrl {
	$api_url = "";
	function __construct ($key = "YOUR_API_KEY") {
		// set up the API key if it exists
		$this->key = $key;
	public function shortenUrl ($url) {
		// concatenate the API url
		curl_setopt($ch,CURLOPT_URL,$this->api_url . $this->key);
		// send the json ecoded long version of the url
		curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
		// execute
		$result = curl_exec($ch);
		// close
		// 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 *