Advertisement

How to Create a Photo Gallery using the Flickr API

by

Flickr is, without doubt, the biggest and best photography website on the internet. There are lots of widgets, badges and plugins which allow you to display your latest Flickr photos on your website, but we'll take it a step further by tapping straight into Flickr and integrating your photostream into your website, giving you a photo gallery that is a breeze to update.


We'll be creating this photo gallery using the Flickr API and phpFlickr . If the letters 'A,P & I' are enough to strike fear into your heart, don't worry, we will take it slow and give full code examples that you can copy.

Final Project

Flickr have also recently launched The App Garden, which is a showcase of tools, toys and sites which use the Flickr API to offer something useful or fun. Once you get to grips with using the API, you can let your imagination conjure up a new way to use it and submit your app.

For this tutorial I am presuming that you already have a Flickr account, and access to a server that runs PHP and PEAR.

The Outline

  • Get a Flickr API key
  • Download the phpFlickr files
  • Build a gallery page to display our thumbnails (with pagination)
  • Make a photo page to show our photos (with previous and next navigation)

Step 1 - Get a Flickr API key

Your API key is your own unique series of numbers and letters which grant you access to Flickr's services. Go here: http://www.flickr.com/services/apps/create/apply/

Here you must decide if you are going to use Flickr for commercial or non-commercial purposes. Flickr provide good explanations as to which you should choose, chances are you'll need a non-commercial API key, which is what I am choosing for this demo.

Follow the steps and fill in all your details.

You should then be presented with your unique key which will appear as a series of random numbers and letters like so:

API key example

You'll also see a number called 'Secret;' ignore that for now. For this exercise we only need the key; make a note of it as we'll need it soon.

If you use the API to build a cool tool or site later on, you might want to submit and feature whatever you build in the Flickr App Garden. You can click on 'Edit app details' to fill in the info.

Pay particular attention to the tips and advice given in the API Terms of Use and the Community Guidelines, if you abuse it, you'll lose it.

Now on to the exciting stuff...

Step 2 - Download phpFlickr 

phpFlickr is a project by Dan Coulter. It is a class written in PHP which acts as a wrapper for Flickr's API. The files process the data provided by Flickr and return arrays in PHP, which we use to display our photos

We need to download the files that we will later include in our webpage, and will do all the complicated work for us. Visit phpflickr.com or skip straight to the download page at Google Code. In this demo, we'll be using the zip file: phpFlickr-2.3.1 (zip)

Download link

Download and unzip it. For this tutorial, we only need the PEAR folder and the phpFlickr.php file. Upload the files to your web directory

Step 3 - Basic Setup and Simple Configuration  

Now we have all we need to connect with Flickr and retrieve our photos. We'll make two pages: one to show our thumbnails and one to show the photo. All of the code will be available as complete pages at the end of the tutorial.

These code examples are all working on the basis that your files are on the root of your server - or all in the same folder. Before anything else, we need to create a cache folder in order for phpFlickr to work properly. Create a folder called 'cache' in your web directory and give it writable permissions (CHMOD 777).

Now we'll build a page that displays our thumbnails and has some simple paging. In the example gallery, this is index.php - and looks like this.

Before we go any further, we need to set two main variables in the config.php file.

Open config.php. You'll see it's just asking for two things: your API key and your Flickr username.

First, enter your API key - the long random set of numbers and letters you were given earlier on by Flickr. Keep your info inside the quote marks.

// insert your API key
$key="ENTER YOUR FLICKR API KEY HERE";

Now for your Flickr username; this is not your Yahoo sign-in username or your Flickr screename - but the username you use for Flickr itself. To double check, sign in to Flickr and look at the top of the page where it says 'Signed in as...' - that is your username. So let's declare our username as a variable:

// enter your Flickr username 
$username="YOUR FLICKR USERNAME HERE";

Save the changes to config.php and upload - you shouldn't need that file again.

Step 4 - Building the Thumbnails Page

Final Project

On to the page itself. Here's a breakdown of what we are doing at the top of the page, which cues up everything ready for the action:

We are going to include some Previous and Next links with a small bit of code further down the page. The thumbnails we are going to show depend on what page we are on, so we run a simple if statement which will grab our page number. If there's a 'fpage' query in the url, use that. If not, we are on page one.

<?php
  // get page number from the url - if there isn't one - we're on page 1
  $page = isset($_GET['page']) ? $_GET['page'] : 1;

Next we include the core phpFlickr file that has everything we need in it communicate with Flickr.

// inclue the core file
  require_once('phpFlickr.php');

Now we fire up a new class from the phpFlickr file using our API key that we got earlier.

// Fire up the main phpFlickr class 
$f = new phpFlickr($key);

phpFlickr uses caching to speed the process up. There are options of using a database technique but for this tutorial we will use the simpler cache folder option. We need a folder called 'cache' that is writable, meaning that the system has access to it and can alter its contents. To do this set the folders' permissions to 777 via your FTP program. Then we add this line to enable it:

$f->enableCache("fs", "cache");

We call the people_findByUsername method which returns an array:

$result = $f->people_findByUsername($username);

From that array, we also need your unique user id (your Flickr id that look like this: 11221312@N00, declared here as $nsid) which we get like so:

// grab our unique user id from the $result array
  $nsid = $result["id"];

Next, we call the people_getPublicPhotos method, which again returns an array that we will call $photos. In this line, we are also passing through our id which we got in the line above ($nsid). NULL refers to the 'extras' option which we're not concerned with right now. We are also stating the number of thumbnails we want to display (21), and are passing through the page to start on ($page) which relates back to the $page variable from the top of the page:

 $photos = $f->people_getPublicPhotos($nsid, NULL, NULL, 21, $page);

The last bit we need to set the page up is a little bit of info we need for the paging to work. We access the $photos array we created above, and pull out the the total number of pages, plus the total amount of photos in our photostream:

$pages = $photos[photos][pages]; // returns total number of pages
  $total = $photos[photos][total]; // returns how many photos there are in total
  ?>

Notice we're closing the php section off here with the ?> Now we have all we need to get the first 21 thumbnails from our Flickr photostream and display them. We'll carry on with the page now, adding some html, using PHP to show the images, and include some simple paging links. So let's start by writing some basic html.

 <!DOCTYPE html  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Nettuts Flickr Gallery Demo</title>
</head>

<body>

<h1>My photo gallery</h1>
<div id="thumbs">

Nothing out of the ordinary here; just setting up the html and starting an area for the thumbnails. The next step is to fill our div called 'thumbs' with our thumbnails like so:

Thumbnails example

Note we're opening php again with <?php:

We'll use a foreach loop to run through the $photos array and to get to the photo element ($photo), which holds the info we need for the thumbnails.
See the comments in the code for an explanation of what's going on:

<?php
// loop through each photo
 foreach ($photos['photos']['photo'] as $photo) {
  
// print out a link to the photo page, attaching the id of the photo
         echo "<a href=\"photo.php?id=$photo[id]\" title=\"View $photo[title]\">";
    
// This next line uses buildPhotoURL to construct the location of our image, and we want the 'Square' size
// It also gives the image an alt attribute of the photo's title
       echo "<img src=\"" . $f->buildPhotoURL($photo, "Square") .  "\" width=\"75\" height=\"75\" alt=\"$photo[title]\" />";

// close link 
      echo "</a>";

// end loop
}
?>

</div><!-- close thumbs div -->

We're almost done with the main page. Chances are, you have more than 21 photos in your Photostream; so we'll need to add some paging with some Previous and Next links so we can move to the next 21 thumbnails. The links look like this:

Pagination example

 This code relies on the line we had at the top calling the $page variable. When our code calls in the photos from Flickr, it also uses the $page variable to know where to start - look back at the line where we called 'people_getPublicPhotos' and you'll see that we passed in the $page variable there as well. That value is the backbone of this little paging arrangement. We'll open a paragraph with the id of 'nav', open up the PHP tags, and define our 'back' and 'next' variables:

<p id="nav">
<?php
// Some simple paging code to add Prev/Next to scroll through the thumbnails
$back = $page - 1;
$next = $page + 1;

Next we handle the actual 'Previous' and 'Next' links by checking that we're not on the first or last page, the close off php and close the 'p' tag.

// if it's not the first page
if($page > 1) {
echo "<a href='?page=$back'>&laquo; <strong>Prev</strong></a>";
}
// if not last page
if($page != $pages) {
echo "<a href='?page=$next'><strong>Next</strong> &raquo;</a>";}
?>
</p>

Now we refer back to some values we had at the beginning to display a little more about where we are in the gallery:

<?php
// a quick bit of info about where we are in the gallery
echo"<p>Page $page of $pages</p>";
echo"<p>$total photos in the gallery</p>";
?>

And to abide by Flickr's terms and finish the page off, we'll add:

<p>This product uses the Flickr API but is not endorsed or certified by Flickr.</p>

</body>
</html>

That's everything we need to produce a page that displays the latest 21 photos as thumbnails with a simple Prev / Next navigation. Just like the homepage on the demo. Next up: the page that displays our photo.

Step 5 - Build a Page to Display Single Photos

Single Page

Now that we have our thumbnails, we need a page to show the full image when one is clicked on. Here is the code for photo.php, which the thumbnails link. We start this page similarly to the index page, but instead of the page number, we want the id of the photo which has been passed in the url from our thumbnail page:

<?php

// Get id of photo
$id = isset($_GET['id']) ? $_GET['id'] : NULL;

//include the core file
require_once('phpFlickr.php');

// Fire up the main phpFlickr class 
$f = new phpFlickr($key);

// cache folder again, permissions set to 777
$f->enableCache("fs", "cache");

Now we need to gather some info from Flickr about the photo such as the photo's id number, its dimensions, where it sits in relation to other photos (context) and the url of the image.

// access the getInfo method, passing in the photo's id
$photo = $f->photos_getInfo("$id", $secret = NULL);

// pass the photo's id to the getSizes method to get the dimensions of our image
$photosize = $f->photos_getSizes("$id", $secret = NULL);

// we want the dimensions of the medium size which we get from the $photosize array in the previous line
$size = $photosize[3];

// again passing the photo's id through we get the context, which tells us which photos are before and after the current id
$context = $f->photos_getContext("$id");

//  the buildPhotoURL method does pretty much what you'd expect - build the  photo URL, we pass in $photo and the size we require to return the  image URL e.g.  http://farm4.static.flickr.com/3108/3175330082_0bf4b22e47.jpg
$photoUrl = $f->buildPhotoURL($photo, "Medium");

// This tells us who the owner of the photo is.
// This is an important part to include as we want our gallery to show  only our photos and not pull in other users' photos - more of an  explanation about this in the notes at the end
$owner = $photo["owner"]["username"];

// We only want the photo if it belongs to us - so if our username  is the same as the owner of the photo... we'll write out the page and  show it 
// more info on this at the end of the tutorial
if($username == $owner){
?>

Now we are primed for the rest of the page with the juicy bits.

<!DOCTYPE html  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<!-- Let's get in there straight away and get the photo's title -->
<title>
<?php
// We access the $photo array and grab the title of the photo to use as the document title
echo $photo[title]
 ?>
</title>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>

<body>

<h1>Photo gallery</h1>

<div id="photo">
<?php
// The photo's title once again
echo"<h2>$photo[title]</h2>";

// The photo itself, you'll recognise $photoUrl from above where we  built the photo's url, we are also accessing the $size array that we  prepared earlier to get the width and height
// and the title once again 
// We'll also make it link to the version on Flickr for good measure
echo"<a href=\"http://flickr.com/photos/$username/$photo[id]/\" title=\"View $photo[title] on Flickr \">";
echo"<img src=\"$photoUrl\" width=\"$size[width]\" height=\"$size[height]\" alt=\"$photo[title]\" />";
echo"</a>";

// The photo's description
echo"<p>$photo[description]</p>";
?>
</div><!-- end photo -->

Now we have our photo... and we are almost done. This last bit may look a bit tricky but don't be put off by it. It has to do with the photo's context, as in, which photo comes next in the stream and which one was previous to it. Just like you see on people's Flickr galleries. The reason there seems a lot of code is because for this to work best, we have to check to see if there is a photo before or after the current photo. If there isn't, we don't want a link, instead we insert normal text and a dummy image (noimg.png).

<div id="context">
<?php
// if there is a previous photo...
if($context['prevphoto']['id']){echo"<a  href=\"?id=".$context['prevphoto']['id']."\" title=\"Prev:  ".$context['prevphoto']['title']."\"><img  src=\"".$context['prevphoto']['thumb']."\" width=\"75\" height=\"75\"  /></a>";

} else {
// if not - show the blank filler image
echo"<img src=\"noimg.png\" width=\"75\" height=\"75\" alt=\"No photo\" />";
};

// if there is a next photo...
if($context['nextphoto']['id']){echo "<a  href=\"?id=".$context['nextphoto']['id']."\" title=\"Next:  ".$context['nextphoto']['title']."\"><img  src=\"".$context['nextphoto']['thumb']."\" width=\"75\" height=\"75\"  /></a>";
} else {
// if not - show the blank filler image
echo"<img src=\"noimg.png\" width=\"75\" height=\"75\" alt=\"No photo\" />";
};

echo"</div>";

echo"<p>";
// if there is a previous link, write a link - if not, just the text
if($context['prevphoto']['id']){echo"<a  href=\"?id=".$context['prevphoto']['id']."\" title=\"Prev:  ".$context['prevphoto']['title']."\">&laquo; Prev</a>";}  else {echo"&laquo; Prev";};
echo" | ";
// if there is a next link, write a link - if not, just the text
if($context['nextphoto']['id']){echo"<a  href=\"?id=".$context['nextphoto']['id']."\" title=\"Next:  ".$context['nextphoto']['title']."\">Next  &raquo;</a>";}else {echo"Next &raquo;";};
echo"</p>";
?>

</div><!-- end context -->

And to finish the page off, we'll include a link back to the main gallery, a bit of text for Flickr and close off the html.

<p>&laquo; <a href="/">Main gallery</a></p>

<!-- To abide by Flickr's terms - you must include this text -->
<p>This product uses the Flickr API but is not endorsed or certified by Flickr.</p>

</body>
</html>

Hold up! One more thing... we finish the if statement from just before the html began... again, see the notes at the end about why we do this.

<?php
} // end if for owner
?>

And there you have it. A photo gallery for your website, powered by your Flickr account. Take a look at the demo page to review how it looks with a bit of extra markup and styling added. This is a very basic implementation of the Flickr API; it just scratches the surface of what you can do, but it does provides a nice photo gallery for your site/blog which you can easily update and maintain via Flickr.

NOTES & EXTRAS

  • In this tutorial we are retrieving a user's public photos. Within photo.php, we reference $owner in this tutorial. At this point we are ensuring that the photo displayed belongs to the owner of the photograph. If we leave this out, your photo page can pull in any user's public photo, and that is obviously not what we want. This goes back to the advice Flickr provides in their guidelines.


    You should use the API to access your own images only or those which you have permission to use. If you display someone else's pictures, you should mention the name of image owner and name of the image. Flickr also say "...pages on other web sites that display content hosted on flickr.com must provide a link from each photo or video back to its page on Flickr."

  • There are other ways to display your photos using the search method in the API, but it is a bit more complicated and requires you to provide authentication - in other words, use the API to log in and let Flickr know it really is you - more info on that can be found here.

  • This demo is a very simple example of what you can do with the Flickr API. You can take it much further and in fact do pretty much everything Flickr does: get photo sets, show tags and comments, display private photos, even upload images. Take a look at the API documentation here: http://www.flickr.com/services/api/ You can cross check the methods against the phpFlickr.php file.
  • Just as we called in our photos using $photos = $f->people_getPublicPhotos($nsid, NULL, 21, $page); you can do the same with a set. For example, $photos = $f->photosets_getPhotos("$set", $extras, $privacyfilter, 21, $page); is a way to get 21 photos per page from a set, where $set = the set id (something like 72157594488289220), then using foreach ($photos['photo'] as $photo) {... to get the images etc.
  • If you need to see which part of the array you need, you can use print_r() to list out the array and see how to find to the value you need. Surround it with <pre> tags to make the output legible.

  • The file paths in this demo all work on the assumption that everything is in the same folder (or all on the root) - feel free to move stuff about but be sure to change the paths
  • Huge thanks to Dan Coulter for wrting the excellent phpFlickr. Be sure to take a look around the phpFlickr documentation: http://phpflickr.com/docs/ for more tips and advice on taking things further

Have fun, and show us what you come up with!