Google URL Shortener PHP Class

By  on  

Google has had a URL shortening domain for quite a while now but it wasn't until recently that Google exposed the URL shortening API to the public.  I took a few minutes to review their API and created a very basic GoogleUrlApi class that will shorten long URLs and expand shortened URLs.

The PHP

The class itself is quite compact and the code should be easy to read:

// Declare the class
class GoogleUrlApi {
	
	// Constructor
	function GoogleURLAPI($key,$apiURL = 'https://www.googleapis.com/urlshortener/v1/url') {
		// Keep the API Url
		$this->apiURL = $apiURL.'?key='.$key;
	}
	
	// Shorten a URL
	function shorten($url) {
		// Send information along
		$response = $this->send($url);
		// Return the result
		return isset($response['id']) ? $response['id'] : false;
	}
	
	// Expand a URL
	function expand($url) {
		// Send information along
		$response = $this->send($url,false);
		// Return the result
		return isset($response['longUrl']) ? $response['longUrl'] : false;
	}
	
	// Send information to Google
	function send($url,$shorten = true) {
		// Create cURL
		$ch = curl_init();
		// If we're shortening a URL...
		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);
		// Execute the post
		$result = curl_exec($ch);
		// Close the connection
		curl_close($ch);
		// Return the result
		return json_decode($result,true);
	}		
}

The constructor requires your Google API key.  A second argument may be provided to the URL of the Google API.  As the API is currently in version 1, changing this URL would be more harmful than useful.  The class features two main methods:  shorten and expand.  Each method takes the long or short URL, contacts Google, and returns its counterpart.  If no counterpart is found, or the Google URL Shortener API is down, a result of false is returned, so please be sure to use your own error handling.

Now let's create an instance of GoogleUrlApi to shorten and then expand a URL:

// Create instance with key
$key = 'xhjkhzkhfuh38934hfsdajkjaf';
$googer = new GoogleURLAPI($key);

// Test: Shorten a URL
$shortDWName = $googer->shorten("https://davidwalsh.name");
echo $shortDWName; // returns http://goo.gl/i002

// Test: Expand a URL
$longDWName = $googer->expand($shortDWName);
echo $longDWName; // returns https://davidwalsh.name

The shorten() and expand() methods return their counterparts, as expected.  Quite painless, no?

The Google URL Shortener API provides much more than what my class provides, including user URL listing and usage tracking.  My class provides only the basics;  I'm assuming that 90%+ care only about getting the URL shortened so I've catered to that audience.  I had also thought about adding a caching mechanism to the class but since most everyone has their own method of caching information, I thought it best to leave that out.  Hopefully this class has some use for you all!

Recent Features

  • By
    7 Essential JavaScript Functions

    I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener and attachEvent.  Times have changed but there are still a few functions each developer should...

  • By
    Create a Sheen Logo Effect with CSS

    I was inspired when I first saw Addy Osmani's original ShineTime blog post.  The hover sheen effect is simple but awesome.  When I started my blog redesign, I really wanted to use a sheen effect with my logo.  Using two HTML elements and...

Incredible Demos

  • By
    Create a Brilliant Sprited, CSS-Powered Firefox Animation

    Mozilla recently formally announced Firefox OS and its partners at Mobile World Congress and I couldn't be more excited.  Firefox OS is going to change the lives of people in developing countries, hopefully making a name for itself in the US as well.  The...

  • By
    Image Reflections with CSS

    Image reflection is a great way to subtly spice up an image.  The first method of creating these reflections was baking them right into the images themselves.  Within the past few years, we've introduced JavaScript strategies and CANVAS alternatives to achieve image reflections without...

Discussion

  1. Great! you beat me to it, thanks

  2. Good, this will help a lot….

  3. It’s useful. thank you for sharing this.

  4. Raymond trangia

    What a nice tutorial just like

    the tinyurl and the bitly

    Hope i can put that in my site concept

    http://goo.gl/YK54o

  5. chris

    nice, i wrote a shell script to use goo.gl url shorten and reverse, before you needed an api key

    • Did you update it to push the API key? If so, I’d love to see it.

  6. Since the API Key is unique for each website, doesn’t it make sense to implement the singleton pattern?

    • I was going to, but since your URLs are saved to your account, I thought it somewhat possible to want to use different keys in the same script. In 99% of cases, you’re probably right.

  7. Awesome..

    With your permission, I’ll do a .NET version of this..

    Erik

  8. Here’s the .NET version : https://github.com/erikzaadi/GoogleUrlApi.net

    Thanks!

    • You are awesome! Thanks a lot!!

  9. Very Awesome.. nice tutorial.. :)

  10. I do not work. returns me blank page.

    • Do you have an API key? Can you share your code?

  11. Very nice , thanks david

  12. YOU ROCK

    I searched all over Google for an example (im a hack)

    THANK THANK YOU

  13. Vron

    It doesn’t work. It returns a blank page. I’m using my API key of course.

    • it’s probably a PHP Version problem… requires 5.3 ?!?!?!

    • Bernardo Gui

      Perhaps your webspace provider blocks cURL requests (allthough phpinfo() shows “cURL support = enabled”) like mine does.

    • Beniston

      For all those who get blank pages:

      1. Try including the below in the curl

      curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
      

      2. In the apis/console page of your google code account enable the url shorten service.

  14. This is a nice article..
    Its very easy to understand ..
    And this article is using to learn something about it..

    c#, dot.net, php tutorial

    Thanks a lot..!

  15. If for you this code does not work – check out what you get from curl_exec() if you get FALSE, then try adding one more curl option:

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    

    This helped me. Without this SSL connection is dropped (shows that certificate validation failed).

    • I went through countless tutorials and only got my code to work after reading your comment. Thank you!!!

  16. Great post man, thanks for this!

  17. Great Post David, Thank you very much!!

    Endijs, your post is very useful for me!! Thanks.

  18. This saved me at least 0:45h. There must be a fairy tonight – thanks so much! But please, update your code-viewer plugin. If i press “copy” it encodes “>” as “>” all the time (FireFox 6.0). Cheers from Germany.

  19. Hey David,
    I Need Some Help in importing contact list of gmail,hotmail
    i some how got the yahoo one
    can you suggest something ?

  20. and nice work with inbox :)

  21. Khanh

    Thank you so much for this class!! You rock!!!

  22. Juan

    Sorry but can you help me?? When I try to get the short URL I get

    { “error”: { “errors”: [ { “domain”: “global”, “reason”: “invalid”, “message”: “Invalid Value”, “locationType”: “parameter”, “location”: “resource.longUrl” } ], “code”: 400, “message”: “Invalid Value” } }

    Do you know which can be the problem? Thanks a lot!

  23. Vasim Padhiyar

    which api key should i pass with request ?

  24. This is sweet!! I will try to use this goo.gl service on my site

    thanks for sharing

  25. No output showing !!

  26. Great script, thanks.

  27. Jay

    I’ve ended up on your blog so many times… it almost feels like asking an old friend ;)

    Thanks for this class, perfect.

    p.s. your template has issues with google chrome…

  28. Nikhil Dixit

    Awesome post…worked perfectly fine for me.

    Can you please explain, how api key works. Should I always generate key from Google API console? The key you provided didn’t work for me.

    • API keys can be created at Google’s website.

  29. thanks, it works just like a charm. by the way is there any limitations using the free api key?

  30. { “error”: { “errors”: [ { “domain”: “global”, “reason”: “required”, “message”: “Required”, “locationType”: “parameter”, “location”: “resource.longUrl” } ], “code”: 400, “message”: “Required” } }

  31. If all configuration is ok and still you are getting blank page then try to generate API key using new google account….

  32. Nipun

    Great script! Excellent working.

  33. It’s GREAT ! Thanks a lot for that !

  34. Hi, I’ve a question!

    If I’m using Api key, I am certain that the short url created is unique and “eternal”?

    Thx!

  35. Thanks for this code. the shorten is working well but the expand is returning empty. what should i do to make the expand function work?

  36. Really Awesome, It helped me a lot, wonderful post…..

  37. Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your site? My blog site is in the exact same niche as yours and my users would definitely benefit from a lot of the information you provide here. Please let me know if this okay with you. Cheers!

  38. ringo

    Hi, I’m using this library and when I put in a loop to generate thousands of short addresses, it starts to return empty values​​.

    What could be happening?

    • Google’s probably cutting you off, you’re making too many requests at once.

  39. Could not get this to work with # marks on deep linking – google rejected the format.

  40. David, I must tell you that you are indeed doing a very good job.Thanks

  41. Thanks for this article :) I’m using another url shortener script called shrinky but I’ll try this script to see how it works. Thanks again

  42. komay

    after including this curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); it works thanks

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!