Lightweight PHP Picasa API Version 3.0

Monday, April 7, 2008 at 9:36 AM
After weeks and weeks of toiling away at my desk in my free time, I've finally put the finishing touches on Version 3.0 of my Lightweight PHP Picasa API. I think the extra time has not been wasted, as this version is about a thousand times more robust and feature-rich than versions 1 and 2, as well as being a lot easier to use. For easy access, here are the important links:

Download the API source code

View the Documentation

View the bug and feature request list

Here I'll list the major features, and then go into greater detail on each one. Features include:
  • Automatic query building through the Picasa class
    • Pass in the parameters for your request and the member functions will build and send the query for you.
  • Robust error handling through the Picasa_Exception class
    • 8 different Exception classes that can be caught individually, all of which extend Picasa_Exception to allow any level of granularity your situation requires.
  • Easy-to-use implementation of authorizations through the Picasa class
    • Supports Client Login or AuthSub
    • Supports persistent authorizations using browser cookies
  • Added previously unsupported operations
    • Suports not only fetching feeds, but also posting and deleting images, albums, comments, and tags, as well as updating images and albums.
    • Include access to public and private albums.
  • Added several fields to existing classes
    • Added support for Exif data, GML coordinates, among others
  • Comprehensive documentation using PHPDoc
    • View the Javadoc style manual here.
  • 100% backwards compatible with versions 1 and 2
  • It's still "lightweight"
    • No special requirements, just PHP 5
    • Less than a third the size of the Zend framework
Automatic query building through the Picasa class
The Picasa class is certainly the biggest addition to the new version. It's really the only object that your client code will ever have to instantiate. It handles both authorization as well as data requests and manipulations (posting and updating images, etc). The nice part about how it handles data requests is that you'll literally never have to formulate a query string again. Pretty much any type of feed that can be requested from Picasa is supported through just a few different methods in this class. Just instantiate a Picasa object and then call the method you're looking for. For instance, to get all albums for user "goldplateddiapers" (that's me), use the following code:
$pic = new Picasa();
$albums = $pic->getAlbumsByUsername("goldplateddiapers");
Now $albums will hold a Picasa_Account object that has an array of all my albums. To see exactly what is in a Picasa_Album, you can look at the manual, or you can just print the object. I've added very handy __toString() methods for all the objects. So add this line and see what you get:
print $albums;
If you're viewing this in Firefox (which you should be!), view the page source to get a prettier display. The output should be a nicely formatted printout of every field in the object. Each one of those fields has a getter method so that you can access the data you see.

Of course, oftentimes your request will not be as simple as getting all images from one user. So each of the "get" functions in the Picasa class take a plethora of parameters to suit your needs. For instance, take a look at the definition for Picasa::getImages():
public function getImages($username=null, $maxResults=null,
$startIndex=null, $keywords=null, $tags=null,
$visibility="public", $thumbsize=null, $imgmax=null);

As you can see, none of these parameters are required. Which ones you should supply depend on what you're looking for. To find the first 250 images in Picasa tagged "lolcats", do the following:
$pic = new Picasa();
$images = $pic->getImages(null, 250, null, null, "lolcats");
Now $images will be a Picasa_ImageCollection object with an array of up to 250 of your favorite lols. The same format follows for any methods in the API starting with "get". And of course, all of the parameters for each method are fully described in the documentation.

One thing to be careful of is that all combinations are not supported by Picasa. For instance, calling just Picasa::getImages() with no parameters, Picasa itself will probably yield an error, which will be thrown as a Picasa_Exception with the error message retrieveable through Picasa_Exception::getMessage(). See the next section for more information on exception handling. I've left it up to the client code to send acceptable requests; the API will only throw an exception if Picasa itself responds with an error, the API doesn't catch invalid combinations of parameters and thus they're not documented here. You'll have to play around with different parameter combinations or check Picasa's Developer Guide.

Robust error handling through the Picasa_Exception class
The previous versions of the API didn't do much in the way of error handling, and this aspect is probably the second biggest improvement since then. There is one main exception class, called Picasa_Exception, that all exceptions thrown from the API will be at least subclassed from. It's not an abstract class, so oftentimes an instance of Picasa_Exception itself will be thrown, but a more specific subclass will be thrown when appropriate. Take a look at the subclasses in the documentation or the source code, they're all listed in the Picasa_Exception class.

The Picasa_Exception class extends PHP's Exception class and adds a few nice fields to have. The first is Picasa_Exception::$url, which will contain the offending URL if the exception resulted in a bad request to Picasa. If the exception wasn't thrown as a result of a bad request, this field will be null. The other field that can be useful is Picasa_Exception::$response, which holds the complete response that the exception was thrown as a result of, again only if the exception is thrown because of a bad request.

To give you some background on how the API knows it should throw an exception when it's given a bad request (skip this paragraph if you don't care), basically the method that is used for executing requests (Picasa::do_request()) checks for a response of 200 or 201. If that's not found, it passes the response header to a method (Picasa::getExceptionFromInvalidPost()) that determines which kind of exception to throw. It saves the error message given by Picasa as the result of Exception->getMessage(). However, sometimes the body of the response, even if it was not a 200 or 201 response code, can be useful. For example, if a client is trying to authenticate using Client Login and Picasa requests a CAPTCHA challenge, the response code is 403, but fields are set in the body identifying the URL to the CAPTCHA challenge and the CAPTCHA's token value. The API uses the Picasa_Exception::getResponse() method to get the returned response, determine that it is a CAPTCHA challenge, and parse out the required fields.

The only other exception class in the API that adds any fields to the base Exception class is Picasa_Exception_CaptchaRequiredException. This (as you might have guessed) is thrown when a CAPTCHA challenge is requested by Picasa upon attempting to gain authorization. If you're unfamiliar with this operation, Picasa will ocassionally require a user attempting to login using Client Login to type in letters that appear in a supplied image in order to guarantee that the user is a real person. To login after a CAPTCHA is requested, you do exactly what you did to log in the first time, this time passing in the user's CAPTCHA answer and a token supplied by Picasa (see the next section for how the API deals with logins and CAPTCHAs). The Picasa_Exception_CaptchaRequiredException contains the method Picasa_Exception_CaptchaRequiredException::getCaptchaUrl() for getting the URL to the image to display, the method Picasa_Exception_CaptchaRequiredException::getCaptchaToken() for getting the token to pass along with the re-attempt at authorization, and the methods Picasa_Exception_CaptchaRequiredException::getUsername() and Picasa_Exception_CaptchaRequiredException::getPassword() for getting the user's username and password that they originally used when attempting to sign in.

As an example of how to use the Picasa_Exception classes effectively, here is an example of client code attempting to log in (see the next section for details about how to use the authorization functionality, but I think you can infer what the code is generally doing). Let's assume I've just requested the user's username and password in a form, using the POST method:
// Get the username and password from the POST superglobal
$user = $_POST['username'];
$password = $_POST['password'];

$pic = new Picasa();
$pic->authorizeWithClientLogin($user, $password);
} catch (Picasa_Exception_CaptchaRequiredException $ce) {
print "Please enter the letters you see in the image: ";
print '<img src="'.$ce->getCaptchaUrl().'" />';

/* Put code for generating a form with an input field, setting $ce->getCaptchaToken(),
* $ce->getUsername(), and $cd->getPassword() as hidden fields here
} catch (Picasa_Exception_InvalidUsernameOrPasswordException $ie) {
print "The username or password you have entered is invalid.";

/* Put code for handling re-logins here
} catch (Picasa_Exception $e) {
print "Your attempt to login has failed: ".$e->getMessage();

/* Put code for handling relogins here
Easy-to-use implementation of authorizations through the Picasa class
Previous implementations of the Lightweight PHP Picasa API did not support authorizations in any way. This suited my needs personally, but left a lot of people out of luck or on their own to throw something together. With the addition of the Picasa class, though, comes a suite of methods and fields for gaining and keeping authorizations. The first thing you need to know about is the difference between Client Login and AuthSub. Client Login allows you to enter a user's username and password, while AuthSub requires your client to redirect the user to a Google-hosted secure page to enter their username and password. The Picasa class supports both.

To authorize a user using Client Login:
  1. Get their username and password
  2. Call Picasa::authorizeWithClientLogin(), passing in their username and password.
At this point, if the authorization was successful, you have an "authenticated" Picasa object. Now, using this Picasa object, you can do operations that the current user is authorized to do, such as accessing their private albums, posting photos and albums to their account, etc. If the authorization was unsuccessful, a Picasa_Exception is thrown. See the previous section for instructions on how to handle such exceptions.

To authorize a user using AuthSub:
  1. Redirect the user to the Google login page using Picasa::redirectToLoginPage()
  2. On the page supplied in the $next parameter or Picasa::redirectToLoginPage(), call Picasa::authorizeWithAuthSub().

These steps automate a few things that you could also do manually, depending on what your intentions are and what your server configuration gives the API access to. First, if you want to redirect the user manually, you can call Picasa::getUrlToLoginPage() just to get the URL that you should send the user to, and then redirect them using your client code however you want. Second, if the API doesn't have access to the $_GET superglobal (which the token required for Picasa::authorizeWithAuthSub() is in), you can get the "token" parameter out of the URL however you normally would and manually pass it as the first parameter in Picasa::authorizeWithAuthSub(). If it's not passed in, or null is passed instead, the method will look in the $_GET array for the token and if it's not there, throw a Picasa_Exception_FailedAuthorizationException.

A neat feature that is built into the API is persistent login through the use of cookies. Cookies are used because there's no server-side caching mechanism supplied with the API. So by default, if you authorize a Picasa object, it will store the authorization token and the type of authorization used (AuthSub or Client Login) in the users browser cookies. Tokens don't expire for quite a while, so this allows the user to login once and remain logged in as long as you like. You can use the method Picasa::authorizeFromCookie() and it will automatically look in the user's cookies for an authorization token and authorize the object if it finds one. If it doesn't, false is returned and your client code can prompt the user to login again. So here is a snippet for logging in using AuthSub:
$pic = new Picasa();
if ($pic->authorizeFromCookie() === false) {
//Perform authorized requests here

On the other hand, if you don't want the API to automatically save the token to the user's cookie and you want to save it yourself in a more secure way, you can pass false as the $saveAuthorizationToCookie parameter of either Picasa::authorizeWithAuthSub() or Picasa::authorizeWithClientLogin(). The token is returned from both methods when a successful authorization is established. To then authenticate a Picasa instance, you can either pass the token along with the type of authorization (represented by the public static members Picasa::$AUTH_TYPE_AUTH_SUB and Picasa::$AUTH_TYPE_CLIENT_LOGIN) into Picasa's constructor when you instantiate it, or call Picasa::setAuthorizationInfo(), also passing in the token and type.

It should also be noted here that Picasa actually returns a "single use token", which is only good for one request, when a user attempts to login through AuthSub. However, the API automatically converts the single use token into a session token and saves that value. There is no parameter to turn that feature off because there is no downside to doing it and a single use token is too worthless to warrant another parameter.

Added previously unsupported operations
Now that authorizations are possible, so are authorized operations. I've done my best to provide pretty much any operation available through Picasa's core Data API in this PHP version. So you can post, update, or delete albums and images from an account that you have permission to do so in once you have have an authorized Picasa instance. You can also post or delete comments and tags, and retrieve private feeds.

The methods for posting, updating, and deleting are extremely similar to the methods for retrieving feeds. There are several "posting" methods, just like there are several "getter" methods described in the first section. So let's say you want to post an album titled "Dwight Schrute's One Night Stand" to the account "goldplateddiapers":
$pic = new Picasa($token, Picasa::$AUTH_TYPE_AUTH_SUB);

if ($pic->isAuthenticated()) {
try {
$album = $pic->postAlbum("goldplateddiapers", //Username
"Dwight Schrute's One Night Stand", //Title
"Dwight and Angela exchange cat pictures.", //Summary
"private", //Access rights
"false" //Commenting enabled
} catch (Picasa_Exception_UnauthorizedException $ue) {
print ("You are not authorized to add this album.");
} catch (Picasa_Exception $e) {
print ("An error occured while posting the album: ".$e->getMessage());
} else {
Yeah, I know, the parameter list gets a little ridiculous. However, I've tried to order them in such a way that they will be as short as possible. For instance, had I wanted that album to be public and allow commenting, I could have left off the last two parameters.

Now that you know how to post an album, posting images, comments, and tags are all done the exact same way, though the parameter list varies. You can also update albums and images, although Picasa doesn't allow comments or tags to be updated. Deleting is allowed for all four types of objects. Read the documentation to see exactly which parameters are accepted for each type.

Added several fields to existing classes
The most noticeable difference here is going to be in the Picasa_Image class. The amount of information that is available for each image has just about doubled. You can see that Exif data and GML information are two things that were not supported in previous versions. One thing you will have to look out for, though, is that some of the fields will be null at times. It just depends on what the Atom feed from Picasa applies. To see what fields are null while testing your client code, just print the result of Picasa::getImages() and play around with the parameter values. The __toString() method will be automatically invoked and you can get a nice view of exactly what the instantiation looks like.

There is a cool new feature for some of the getter fields, too, that alleviates some of the problem associated with the null fields. You'll notice in the past that if you request all albums for a single username, the result would have come in the form of a Picasa_Account, which would have an array of Picasa_Album objects. However, those albums would not contain any images, presumably because it would take a lot of extra time to fetch and transfer the information about each image. Now, however, the method Picasa_Album::getImages() will check to see if the $images array is null and fetch a new instance of the current image, pull out the $images array from that instance, and return it. This way, if you want the value, it will always be there. The same logic follows for Picasa_Image::getComments() and Picasa_Image::getTags().

Comprehensive documentation using PHPDoc
I've gone to great lengths to document the entire API, and I finally went through the trouble of generating the docs and hosting them. I think the documentation will be really helpful in using this API, I have literally spent hours preparing it. One thing to note is that it's split up into two packages: Picasa and Picasa_Exception; the latter can be difficult to spot from the documentation's front page, there's a link to it at the very top. You can find all the documentation here.

I did not generate documentation for the Cam folder because it is not really part of the API and shouldn't be used. I attempted to change the code inside those files to utilize the new Picasa class, but the method names and intentions didn't really make sense in the context of the new version. They're still there, for backwards compatibility sake, and they work. However, if you're a newcomer, I would certainly ignore them.

100% backwards compatible with versions 1 and 2
As with the previous versions, drop the code in where your previous code was and you should have no problem. The one caveat is that you have to have had the classes inside the Picasa folder that was provided with the old versions. That folder is no longer the topmost level, the php folder is, so be careful when doing this. And as I stated earlier, the Cam folder is included for backwards compatibility.

It's still "lightweight"It really depends on what you call "lightweight", but I think I've held true. The main thing is that there are no special packages needed with PHP in order for it to work. It was tempting to use the cUrl library or the Http classes, but I just implemented all the HTTP responses and requests myself.

Also, it's still a very easy install. You should be able to drop the files into your include path and pretty much be ready to go right away. A lengthier explanation is given in the README, but there's not a whole lot to it other than that.

The future

Obviously I've spent a lot of time trying to make this a product that people can actually use. I didn't expect to, but it remains to be by far the most popular topic on my blog, so I decided to expand on it. To that extent, I've also opened up a Google Code page for it, which I'll mainly use for tracking issues. You can visit that here. While I can't currently see a reason to make a version 4 of the API, I will certainly have future releases. With the added functionality, there will positively come added bugs, and there are enhancements that I have thought up that I did not get time to implement. So if you find a bug, let me know or add it to the bug list, and I'll probably release an update every month or two. It also really depends on the response, whether or not people seem to like the product. Whatever happens, I'll keep all the download links pointing to the latest release, so you can be sure you're getting the most up to date code.

I made this with the intent of making it easy for PHP developers to harness the Picasa service and create really cool new products, so please do so. As always, if you have any commentary, please leave a comment here or send me an email to tell me what you think. I would love to hear that someone really likes or really dislikes anything about the API. If you have features you'd like to see, feel free to let me know or add it to the issue list. And just in case you missed it at the top:

Click here to download the API

Thanks to everyone who has helped with this and everyone who is using it. Now while the bug list is still at zero and my eyes are still open, I'm going to play my Wii...


Hi Cameron,
Does this API still works with picasa and if it works can you guide me how to post new photo trough your API!
Thank you, Great Work!
Posted by BestpransNET on Wednesday, May 14, 2014 at 3:26 AM.
For those who suffered annoying 'Authorization required' message returned by Google after requesting private albums, some tips:

Extend constructContextArray method in Picasa class with:
just before the definition of $opts.

Then replace every instance of $xmldata = @file_get_contents($url, false, $context); in all class files with the following:

$ch = curl_init();
$timeout = 0;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HTTPHEADER, $contextArray['http']['header']);
$xmldata = curl_exec($ch);

One disadvantage: requires CURL library.

Besides respect for this great tool!
Posted by Kemist on Friday, November 16, 2012 at 10:58 AM.
For those who suffered annoying 'Authorization required' message returned by Google after requesting private albums, some tips:

Extend constructContextArray method in Picasa class with:
just before the definition of $opts.

Then replace every instance of $xmldata = @file_get_contents($url, false, $context); in all class files with the following:

$ch = curl_init();
$timeout = 0;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HTTPHEADER, $contextArray['http']['header']);
$xmldata = curl_exec($ch);

One disadvantage: requires CURL library.

Besides respect for this great tool!

Posted by Anonymous on Friday, November 16, 2012 at 10:57 AM.
Hi Cameron. Nice work. The documentation is very thorough, but I couldn't find any examples, so I've created one here:

The code was written for this:

Many thanks,
Nigel Barber (@mindbrix)
Posted by Mindbrix on Sunday, November 28, 2010 at 4:34 AM.
Hi I just tried your api, I've tried

$pic = new Picasa();
$album = $pic->getAlbumsByUsername("goldplateddiapers");
print $album;

at first it didn't display anything but when I tried to catch an exception, it throws this exception

[ TYPE: Picasa_Exception MESSAGE: An unknown error has occured. REQUESTURL: RESPONSEBUFFER: ] Backtrace: Picasa::getExceptionFromInvalidQuery() in \robdev\Picasa\Account.php at line 245 Picasa_Account->__construct()in \robdev\Picasa.php at line 631 Picasa->getAlbumsByUsername() in \robdev\index.php at line 6
Posted by Rob on Monday, July 12, 2010 at 8:40 PM.
Sandip, take a look at this documentation. The Picasa.clearAuthentication() function will clear all auth information from the Picasa object.
Posted by Cameron on Thursday, March 25, 2010 at 1:01 PM.

I am using this API to get the user's data. It's working fine. Thanks for providing such useful API.

I have one problem regarding the logout feature.

is it possible to logout through API?

Please reply ASAP. It's urgent.
Posted by Sandip on Thursday, March 25, 2010 at 5:19 AM.
Please help me.. I am using the code.
The following is my code:

$f = new Picasa($_GET['token'],3);
$account = $f->getAlbumsByUsername("default",null,null,"private");
$albums = $account->getAlbums();


But after authentication it displays the albums first time.

After that when I refresh the page, I am getting a blank page.

Please tell me what is the solution.
Posted by gargi on Sunday, February 21, 2010 at 10:01 PM.
Found it myself:

You probably need to set allow_url_fopen to true, although I do not see it on your
php info page. That is generally the setting that people have to set.

I set it on and now it is working :-)

Just to let everybody know :-)
Posted by Vampie on Saturday, December 26, 2009 at 6:45 AM.

I'm trying the API, but i always get the error:

Your attempt to login has failed:

even with trying your code:
$pic = new Picasa();
$images = $pic->getImages(null, 250, null, null, "lolcats");

Any ideas?
Posted by Vampie on Friday, December 25, 2009 at 12:39 AM.
Some users seem to have a problem with the include path thing and not all host allow you to change the servers include path via init_set. I actually changed all the 'require_once' lines so they were all including the same path but perhaps it might be easier to just do something like this as a base usage instruction;
In your base script file e.g. index.php use

include_once INCLUDE_PATH./Picasa.php;

Then in the package files you could do something like
require_once INCLUDE_PATH./packagefile.php;
Posted by Guardian on Sunday, November 22, 2009 at 8:46 AM.
Hi cameron,
Nice code, i am using your code and i put test page for getting albums, its returning the xml format array.
upto this i am not getting any issue, after getting that array i need to get the XML source array(i mean separated by every tags), for this you added the function in your source code or i need to add for extracting xml tags data
Posted by sivanantham on Monday, November 16, 2009 at 6:47 AM.
Hi Cameron,

Just wanted to say thanks for your great work. I decided to check out your API because the Zend framework was eating up WAY too much memory, and after playing around with your API I've seen that it uses much less than Zend, and is easier to use also! Keep up the excellent work.

Posted by Anonymous on Wednesday, September 30, 2009 at 5:24 AM.
Great, I'm glad you like it! By the way make sure you catch Version 3.3, which I finished a few weeks ago.
Posted by Cameron on Monday, June 22, 2009 at 10:18 PM.
Haha, it works!!

Thanks Cameron for investing the time in this very useful API!!

Posted by Jeroen on Monday, February 2, 2009 at 1:40 PM.
Great job on the API. It is very useful and very easy to understand given the great documentation. All I wanted was to display my images from picasa on my website and your library made that easy. BTW thanks so much for the quick E-mail response, all my issues are fixed now!

Posted by Brian on Monday, October 20, 2008 at 11:32 AM.
Hi, I cannot make to work the custom sizes
Following the example and adding the custom size at imgmax or imgthumb, always receive the SMALL version
$img = $pic->getImageById($username, $albumid, $image->getIdnum(),null,"640");

And then at the html
echo 'a href="'.$img->getLargeThumb().'" title="'.$img->getDescription.'" class="thickbox" rel="propiedad" /';

You can checkit at

Anybody can help me?

Posted by Bicho44 on Sunday, September 21, 2008 at 9:03 AM.
Hi cameron!
how can I do a next/back button photo in photo page?
Posted by Xavier on Wednesday, September 17, 2008 at 4:52 AM.
Oh! My best wishes and thank you again for taking the time to write this handy library :)
Posted by Nikos Dimitrakopoulos on Wednesday, September 10, 2008 at 1:04 PM.
That's great, thank you! I will get that into the next version when its available for download. I've worked on it a little but unfortunately my pending nuptials have left me with absolutely no time to do anything but wedding plan (as anyone who has looked at my blog in the last two months can tell). :-/ After I get back into the normal swing of things I'll get a new version out, though. Hopefully sometime in October.
Posted by Cameron on Wednesday, September 10, 2008 at 12:57 PM.
Hi there Cameron,
I was using your library (which is really useful by the way) and I found a problem.

I've already posted this in google code with a patch.

Posted by Nikos Dimitrakopoulos on Tuesday, September 9, 2008 at 3:48 PM.
Anonymous comments is something that I would really like to see as well. My workaround is pretty inventive, I think. I wrote all about it in my Comments:Enabled post. I don't think it's appropriate to add directly into the API, but using the API to implement this idea is pretty easy.

On the other hand, maybe it would be a good idea. Writing my own API is really useless unless it offers something that the "official" API doesn't (which is why the next version will have things like methods to copy an image to another album). So maybe anonymous comments wouldn't be bad to have there. I just wouldn't want Google to get after me for potentially compromising the integrity of their comments.

Hope that helps.
Posted by Cameron on Monday, August 11, 2008 at 1:53 PM.
This comment has been removed by the author.
Posted by Cameron on Monday, August 11, 2008 at 1:51 PM.

One thing that Google hasn't implemented yet (I guess) is the support for changing the name on a comment.
I would like to create a photo gallery where the users are able to place comments, either by entering a name or logging in to my site.
Then I would like to add a comment for them, using my own credentials, and specifying the comment authors name.

I guess this is at one hand a stupid thing to add, because you couldn't trust the name of the author anymore. However, in my case, it is stupid that you cannot alter the name.

Do you have any ideas about this, because I checked it out and your API doesn't support giving an author name either.



PS: Check out the current version of the photo gallery on my site (I'm sorry, but it's in Dutch.)
Posted by Tim on Monday, August 11, 2008 at 1:32 PM.
I am sorry, I didn't search enough :P
Thank you, this is a great work !
Posted by John on Saturday, June 7, 2008 at 6:13 AM.