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 class itself is quite compact and the code should be easy to read:

// Declare the class
class GoogleUrlApi {
	// Constructor
	function GoogleURLAPI($key,$apiURL = '') {
		// 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_HTTPHEADER,array("Content-Type: application/json"));
		else {
		// Execute the post
		$result = curl_exec($ch);
		// Close the connection
		// 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("");
echo $shortDWName; // returns

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

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
    Chris Coyier’s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...

  • By
    JavaScript Promise API

    While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready?  Promises are becoming a big part of the JavaScript world...

Incredible Demos

  • By
    Multiple File Upload Input

    More often than not, I find myself wanting to upload more than one file at a time.  Having to use multiple "file" INPUT elements is annoying, slow, and inefficient.  And if I hate them, I can't imagine how annoyed my users would be.  Luckily Safari, Chrome...

  • By
    CSS :target

    One interesting CSS pseudo selector is :target.  The target pseudo selector provides styling capabilities for an element whose ID matches the window location's hash.  Let's have a quick look at how the CSS target pseudo selector works! The HTML Assume there are any number of HTML elements with...


  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

  5. chris

    nice, i wrote a shell script to use 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..


  8. Here’s the .NET version :


    • 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)


  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#,, 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 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”?


  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!