Google URL Shortener PHP Class
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!
Great! you beat me to it, thanks
Good, this will help a lot….
It’s useful. thank you for sharing this.
What a nice tutorial just like
the tinyurl and the bitly
Hope i can put that in my site concept
http://goo.gl/YK54o
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.
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.
Awesome..
With your permission, I’ll do a .NET version of this..
Erik
Here’s the .NET version : https://github.com/erikzaadi/GoogleUrlApi.net
Thanks!
There you go : https://github.com/erikzaadi/GoogleUrlApi.net | http://erikzaadi.com/blog/2011/02/06/GoogleUrlShortenerApiForDotNET.xhtml
Thanks!
You are awesome! Thanks a lot!!
Very Awesome.. nice tutorial.. :)
I do not work. returns me blank page.
Do you have an API key? Can you share your code?
Very nice , thanks david
YOU ROCK
I searched all over Google for an example (im a hack)
THANK THANK YOU
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 ?!?!?!
Perhaps your webspace provider blocks cURL requests (allthough phpinfo() shows “cURL support = enabled”) like mine does.
For all those who get blank pages:
1. Try including the below in the curl
2. In the apis/console page of your google code account enable the url shorten service.
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..!
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:
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!!!
Great post man, thanks for this!
Great Post David, Thank you very much!!
Endijs, your post is very useful for me!! Thanks.
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.
Hey David,
I Need Some Help in importing contact list of gmail,hotmail
i some how got the yahoo one
can you suggest something ?
and nice work with inbox :)
Thank you so much for this class!! You rock!!!
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!
which api key should i pass with request ?
This is sweet!! I will try to use this goo.gl service on my site
thanks for sharing
No output showing !!
Great script, thanks.
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…
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.
thanks, it works just like a charm. by the way is there any limitations using the free api key?
{ “error”: { “errors”: [ { “domain”: “global”, “reason”: “required”, “message”: “Required”, “locationType”: “parameter”, “location”: “resource.longUrl” } ], “code”: 400, “message”: “Required” } }
If all configuration is ok and still you are getting blank page then try to generate API key using new google account….
Great script! Excellent working.
It’s GREAT ! Thanks a lot for that !
Hi, I’ve a question!
If I’m using Api key, I am certain that the short url created is unique and “eternal”?
Thx!
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?
Really Awesome, It helped me a lot, wonderful post…..
No work!! In this site explain other way http://stackoverflow.com/questions/13066919/google-api-url-shortener-with-php
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!
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.
Could not get this to work with # marks on deep linking – google rejected the format.
David, I must tell you that you are indeed doing a very good job.Thanks
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
after including this
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
it works thanks