Oct
16
Posted on 16-10-2006
Filed Under (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/

    Read More   

Comments

mn3nbDwgdB on 13 January, 2007 at 6:23 am #

Hi! Very nice site! Thanks you very much! OlPHPuiCdl3r3


ali on 27 February, 2007 at 12:44 pm #

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


ali on 27 February, 2007 at 1:29 pm #

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?


Anandi Hristina on 19 September, 2007 at 10:01 pm #

your way to beautiful gir. Anandi Hristina.


Mihangel Caiaphas on 21 October, 2007 at 8:48 pm #

damn all these beautiful gir. Mihangel Caiaphas.


Caroline McGowann on 14 February, 2008 at 12:12 am #

I your source code you include the following:

where are these defined?
I am currently trying to solve compatibility issues with IE ad Firefox.


Caroline McGowann on 14 February, 2008 at 12:15 am #

Sorry somehow my last comment is missing content

Where are the following defined:
" "
""
Thanks


Caroline McGowan on 14 February, 2008 at 12:17 am #

Okay one more try where are the followig defined:

mainphotodiv
photos

Both are included as div id parameters in your source code.

Thanks


jay on 14 February, 2008 at 6:27 am #

mainphotodiv is on line #49 in index.php
photos in on line #63 in index.php

both div's are generated inside php functions.


Caroline McGowan on 14 February, 2008 at 11:22 am #

Hi Jay,

Thanks for the response. I am a little confused .. I thought on lines 49 and63 was where this divs were been referenced but where are they defined.

The reason I ask is that I am have a compatibility issue on IE. The ajax.Updater call on line# 117 is hanging and I thought it might be due to the div mainphotodiv. So I just wanted t see how it is defined ..


jeanloui on 22 February, 2008 at 9:56 am #

Hi,

I get the gallery running but I have some problems with the encoding for the titles of pictures and sets:

I have Catalan and Spanish accents and characters (à, è, ó, ç, etc.) in Flickr and I have the mysql database cache set to utf_general_ci for the request and for the response.

I tried to set the response to "latin_general_ci" but it did not fix the problem:

I get "ó" for an "ó"

What I'm doing wrong?

Thanks a lot

jeanloui


jeanloui on 23 February, 2008 at 11:52 am #

Solved! I saved index.php as UTF-8 compatable (BBEdit)


bobby on 6 April, 2008 at 10:30 am #

a7ZvJR Hi! Nice site! Where is a add to favorite button& ;)
http://www.mysite.com


Patricio on 21 April, 2008 at 2:41 pm #

Hey I would like to see an example of how to UPLOAD photos to my flickr account from my website... can you point me on the right direction, or give me an example?


Post a Comment
Name:
Email:
Website:
Comments: