October 16th, 2006

Using phpFlickr to Integrate Flickr Photos on Your Own Site

PHP, by jay.

Over the past couple of weeks I have been working with the phpFlickr class that interfaces with the Flickr API. Integrating with Flickr is part of a side-project that I have going which is to create a single site to display del.icio.us links, Flickr photos, Google office docs and other social networking stuff.

Any how I stumbled upon the phpFlickr class and have been hacking away at a fully integrated photo site to display my Flickr photos. Now don't get too excited because the photos I have are mostly just my daughter (Yes, to those of you with out kids this is a little weird but I assure you it's perfectly normal).

As always I started out with a grand plan to write the ultimate howto guide to the phpFlickr class and so far it's going well but I am reaching a point that it's just too much information for me to cover. So as a compromise I am posting the source code with some instructions so that others can use the code and hack at it them selves.

Download Source Code

Summary
In this tutorial I will explain how to use the phpFlickr API to interact with Flickr and display photos on your own site. phpFlickr is a class that wraps up the Flickr API in a nice well though out package for a PHP developer to work with. It was developed by Dan Coulter and a million thanks go out to him for creating this and giving it away to the rest of us hacks.
Flickr Hacks: Tips & Tools for Sharing Photos Online (Hacks)


The end result is a single php page that displays your Flickr Photo Sets and individual photos on your own site. The code is pretty simple and the most complex part is working with the PHP Object and extracing the correct items and then wrapping them in some HTML. The script works in 3 stages:1) initial view of the primary photo from each photoset, 2) all of the photos from a single photo set and 3) a a slide show of a single photoset using Lightbox JS.

Requirements
phpFlickr
Flickr Account
A MySQL DB for the PEAR Caching
OR
Read/Write access to the FileSystem
script.aculo.us
LightBox JS

All of the above are included in the source code.

History
A few weeks ago my wife asked me why I was always "messing around with cool stuff" as I had put it as opposed to working on our personal site? She said that I am always telling here about this cool Ajax and RSS stuff and some "delicious" thingy but I haven't worked on our site in years. "Why is that?" She went on to say that instead of playing around why don't I fix our photo gallery and make it cool.

She had a good point and I figured I should spend some time working on our original site so it's not so out of date. I started looking a different options for a PHP based Photo Gallery that would be easy for my wife to use and maintain. Some options that came up were Plogger, myGallery Plugin for WordPress, Gallery2 (and the WP Plugin) and ZenPhoto but each one seamed to lack the Web2.0 shinnyness of script.aculo.us. One of the draw backs of being a developer is the "I can build it my self" mentality which made a hosted solution out of the question.

Even though I was against using a hosted solution I started investigating some hosted options like Zoto and Flickr because they both offer an API to hack against. I even found an interesing Picasa hack that used the XML export to build a photo site from but in the end it turned out to be a too much of a hassle.

After more searching I found the Flickr Uploader tool for WinXP/Mac/Linux and I imeaditaly knew that a simple drag n drop tool is what my wife really needed to make it as simple as possible for her to publish photos. BTW- Zoto has a tool that works just like the Flickr tool. I found the Flickr tool here at The Great Flickr Tools Collection where I also found phpFlickr. That's when I decided that I could swallow my pride and compromise by using a hosted gallery but take advantage of the API.

Getting Started
It is important to point out that you need to first authenticate your application with Flickr and obtain the API key information. For simple reading of public photos it's as simple as registering your app here but getting full read/write access is a bit more involved and I will skip that for now.

You can see the fully working example site here.

phpFlicker detailed instructions are here but I'll give you the gist of it.
1) First you need to have the PEAR packages installed on your server.

2) Extract the phpFlickr archive to you working folder.

3) Create an index.php file and include the phpFlickr.php file:

CODE:
  1. require_once("phpFlickr/phpFlickr.php");

4) Add some user credentials:

CODE:
  1. $username = "username";
  2.                 $apiKey = "[APIKEY]";
  3.                 $apiSecret ="[APISECRET]";

5) Instantiate the phpFlickr object:

CODE:
  1. // Create new phpFlickr object
  2.             $f = new phpFlickr($apiKey,$apiSecret);

6) Enable the cache DB:

CODE:
  1. $f->enableCache("db","mysql://[USERNAME]:[PASSWORD]@[SERVER]/[DATABASE]");

7) Get the nsid from the username:

CODE:
  1. $nsid = $f->people_findByUsername($username);

You now have a phpFlickr object ($f) and a userid object ($nsid). Your next step will be to retrieve a PhotoSet object and display a thumbnail from each of your Photo Sets.

How Does this Work
I started with a hand full of basic functions that I wanted and then wrapped them in some UI code. I then call my new functions via a switch case based on an action parameter passed in the URL.

PHP:
  1. $action = rawurlencode($_GET['action']);
  2. $setidrawurlencode($_GET['setid']);
  3. $pidrawurlencode($_GET['pid']);       
  4.    
  5.     switch($action) {
  6.         case 'photoset':         
  7.             returnPhotos($f,$setid);
  8.         break;
  9.        
  10.         case 'view':
  11.             returnPhoto($f,$pid,$setid);           
  12.         break;
  13.        
  14.         case 'detailview':           
  15.             returnPhotosDetailView($f,$setid);           
  16.         break;     
  17.        
  18.         default:
  19.             returnPhotoThumbs($f,$nsid['id']);
  20.         break;                   
  21.    }

This block of code is the brain of the page. As you can see in the switch case that I've got 3 vases and a default case. The default case returnPhotoThumbs($f,$nsid['id']); gets it's values from the very top of the page where we created an instance of the phpFlick class and got some user details.

Getting Photo Set Photos
Now we are going to get a list of PhotoSets and display the primary photo from each one. The function photosets_getList() in phpFlickr.php takes 1 parameter of the userid which is located in $nsid['id'] and return a $photoset object. When we get the $photoset back we'll check to make sure it's not null and then well loop over it and extract the sets one at a time and add the photo and title to a list. To make this a little more reusable and user friendly we are going to wrap the photosets_getList() in another function returnphotosets_getList() which we will pass the $f (phpFlickr object) and the userid.

CODE:
  1. function returnphotosets_getList($f,$user_id){       
  2.         $photosets = $f->photosets_getList($user_id);       
  3.         if(!empty($photosets)){           
  4.             $html .="<ul class='menublock'>";                       
  5.             foreach ($photosets['photoset'] as $set) {
  6.                 $html .= "<li><a href='photos.php?action=photoset&setid=$set[id]'>";
  7.                 $html .= "<img alt='$set[title]' src='http://static.flickr.com/$set[server]/$set[primary]_$set[secret]_s.jpg' />";
  8.                 $html .= "</a></li>";
  9.             }
  10.             $html .= "</ul>";
  11.         }       
  12.         echo $html;       
  13.     }

As you can see this function is just a wrapper around the phpFlickr function photosets_getList but as you know it is bad to mix UI code with Business Logic so we are calling the base function and then wrapping the results in some UI code for displaying it on the page. By doing this we do not need to worry about (too much) when a new version of the phpFlickr is released because we are not altering it in any way. This also gives us the ability to create functions that use a switch case so we can call one base function and then depending on our action we can display the results in a list or grid or drop down.

Getting Photos in a Photoset
The cool thing about the Flickr API and the phpFlickr class is how well it has been thought out and planned compared to other API's. For example now that we have an Array of Photosets we now have a SetID that we will use it to get all of the photos from a selected PhotoSet.

PHP:
  1. foreach ($photos['photo'] as $photo) {           
  2.            
  3.         $html .=  "<a href='".$f->buildPhotoURL($photo, "medium")."'  title='".$photo['title']."' ></a>";       
  4.         $html .= "<img border='0' alt='$photo[description]' src='".$f->buildPhotoURL($photo, "Square")."' id='photo_".$photo['id']."'></a>";                         
  5. }

You'll notice that I am calling the function buildPhotoURL twice: once in the HREF and once in the Image.
I am calling it in the HREF so when you click the photo it will display the photo in medium size and I am calling the same function in the Img to display the photo as a 75x75 pixel square.

I have trimmed this code snippet for readability and clarity because in my code I am using the rel parmeter to creat a LightBox slideshow and I have an OnClick event in a second HREF that makes an Ajax call to get the selected photo. Have a look at the code below to see what I mean.

PHP:
  1. foreach ($photos['photo'] as $photo) {           
  2.            
  3.     $html .=  "<a href='".$f->buildPhotoURL($photo, "medium")."' rel='lightbox[".$photos['id']."]'  title='".$photo['title']."' >";
  4.     $html .= "</a>";
  5.     $html .= "<a href='#' title='".$photo['title']."' onclick='SwapImage(".$photo['id'].",".$photos['id'].");return false;'>";
  6.     $html .= "<img border='0' alt='$photo[description]' src='".$f->buildPhotoURL($photo, "Square")."'id='photo_".$photo['id']."'>";
  7.     $html .= "</a>";
  8.              
  9. }

You can see that the first HREF has an rel parameter which is calling lightbox with the PhotoSet SetID by using the SetID it lets LightBox know that it need to display any photos on the page that have the same rel parameter.

The next part is another HREF that has an OnClick event that swaps the images using an Ajax function call using the PhotID and the SetID.

Lastly is the thumbnail image that is displayed.

On Your Own
The hardest part to all of this is knowing what functions are in the phpFlickr class and what is in the object returned by the Flickr API. I have included some base code to get started with that will provide you with basic interaction with a Flickr account. Now get the source code and start hacking.

Credits
Dan Coulter for the phpFlickr Class http://phpFlickr.com
Andreas Viklund for the killer HTMl Templates - http://andreasviklund.com/
Lokesh Dhakar for Lightbox JS - http://www.huddletogether.com/projects/lightbox2/
The script.aculo.us team - http://script.aculo.us/
The Flickr team for the killer API - http://script.aculo.us/

Back Top

Nifty Corners: rounded corners without images Using phpFlickr to Create a Ajax Enabled Flickr Slideshow

Responses to “Using phpFlickr to Integrate Flickr Photos on Your Own Site”

  1. looks fantastic, but i'm having trouble with an error code on all the pages:

    Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/artfo/public_html/flickrsite/index.php:2) in /home/artfo/public_html/flickrsite/phpFlickr/phpFlickr.php on line 18

    also when i click on a set the first photo loads fine, but if i click on any other i get this error:

    DB Error: connect failed

    I know i'm connecting to the database at some point as data is being written to the database. I'm sure its something simple that i've done, have a look at the page here:
    http://www.artfo.com/flickrsite/index.php

    hope you can help

  2. i've fixed the DB Error: connect failed. I didn't realise that i had to put in the api key / db details in the config.php file. I still get the error message at the top of the screen though.

    Also i've downloaded the source for the flickr gallery from labs.gotfoo.org and it looks like this uses a different version of the ajaxPhoto.php file, as there is "action=next" or "action=prev" in the get call to that script, can you post the source for this file?

  3. Wow, great script. I use it to only show my Flickr sets (albums) on my website. Is it possible to only show the last 6 sets on my Flickr account? Now it shows all my sets (and that's a really big list).

  4. Sorry but it's been so long since I wrote this code that I don't know what it can and cannot do. Most likely the API call to Flickr does not a a limit to how many items it's should return so you would need to put the limit in the display code.