Create Photo Gallery using Flickr API | andi setiawan's blog

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:

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 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.

  1. // insert your API key

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:

  1. // enter your Flickr username

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.

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

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

  1. // inclue the core file
  2. require_once(‘phpFlickr.php’);

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

  1. // Fire up the main phpFlickr class
  2. $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:

  1. $f->enableCache(“fs”, “cache”);

We call the people_findByUsername method which returns an array:

  1. $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:

  1. // grab our unique user id from the $result array
  2. $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:

  1. $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:

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

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.

  1. <!DOCTYPE html  PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
  2. “”>
  3. <html>
  4. <head>
  5. <meta http-equiv=“Content-Type” content=“text/html; charset=iso-8859-1” />
  6. <title>Nettuts Flickr Gallery Demo</title>
  7. </head>
  8. <body>
  9. <h1>My photo gallery</h1>
  10. <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:

  1. <?php
  2. // loop through each photo
  3. foreach ($photos[‘photos’][‘photo’] as $photo) {
  4. // print out a link to the photo page, attaching the id of the photo
  5. echo “<a href=\”photo.php?id=$photo[id]\” title=\”View $photo[title]\”>”;
  6. // This next line uses buildPhotoURL to construct the location of our image, and we want the ‘Square’ size
  7. // It also gives the image an alt attribute of the photo’s title
  8. echo “<img src=\”” . $f->buildPhotoURL($photo, “Square”) . “\” width=\”75\” height=\”75\” alt=\”$photo[title]\” />”;
  9. // close link
  10. echo “</a>”;
  11. // end loop
  12. }
  13. ?>
  14. </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:

  1. <p id=“nav”>
  2. <?php
  3. // Some simple paging code to add Prev/Next to scroll through the thumbnails
  4. $back = $page - 1;
  5. $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.

  1. // if it’s not the first page
  2. if($page > 1) {
  3. echo “<a href=’?page=$back’>&laquo; <strong>Prev</strong></a>”;
  4. }
  5. // if not last page
  6. if($page != $pages) {
  7. echo “<a href=’?page=$next’><strong>Next</strong> &raquo;</a>”;}
  8. ?>
  9. </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:

  1. <?php
  2. // a quick bit of info about where we are in the gallery
  3. echo“<p>Page $page of $pages</p>”;
  4. echo“<p>$total photos in the gallery</p>”;
  5. ?>

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

  1. <p>This product uses the Flickr API but is not endorsed or certified by Flickr.</p>
  2. </body>
  3. </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:

  1. <?php
  2. // Get id of photo
  3. $id = isset($_GET[‘id’]) ? $_GET[‘id’] : NULL;
  4. //include the core file
  5. require_once(‘phpFlickr.php’);
  6. // Fire up the main phpFlickr class
  7. $f = new phpFlickr($key);
  8. // cache folder again, permissions set to 777
  9. $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.

  1. // access the getInfo method, passing in the photo’s id
  2. $photo = $f->photos_getInfo(“$id”, $secret = NULL);
  3. // pass the photo’s id to the getSizes method to get the dimensions of our image
  4. $photosize = $f->photos_getSizes(“$id”, $secret = NULL);
  5. // we want the dimensions of the medium size which we get from the $photosize array in the previous line
  6. $size = $photosize[3];
  7. // again passing the photo’s id through we get the context, which tells us which photos are before and after the current id
  8. $context = $f->photos_getContext(“$id”);
  9. //  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.
  10. $photoUrl = $f->buildPhotoURL($photo, “Medium”);
  11. // This tells us who the owner of the photo is.
  12. // 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
  13. $owner = $photo[“owner”][“username”];
  14. // 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
  15. // more info on this at the end of the tutorial
  16. if($username == $owner){
  17. ?>

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

  1. <!DOCTYPE html  PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
  2. “”>
  3. <html>
  4. <head>
  5. <meta http-equiv=“Content-Type” content=“text/html; charset=iso-8859-1” />
  6. <!– Let‘s get in there straight away and get the photo’s title –>
  7. <title>
  8. <?php
  9. // We access the $photo array and grab the title of the photo to use as the document title
  10. echo $photo[title]
  11. ?>
  12. </title>
  13. <link href=“styles.css” rel=“stylesheet” type=“text/css”>
  14. </head>
  15. <body>
  16. <h1>Photo gallery</h1>
  17. <div id=“photo”>
  18. <?php
  19. // The photo’s title once again
  20. echo“<h2>$photo[title]</h2>”;
  21. // 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
  22. // and the title once again
  23. // We’ll also make it link to the version on Flickr for good measure
  24. echo“<a href=\”$username/$photo[id]/\” title=\”View $photo[title] on Flickr \”>”;
  25. echo“<img src=\”$photoUrl\” width=\”$size[width]\” height=\”$size[height]\” alt=\”$photo[title]\” />”;
  26. echo“</a>”;
  27. // The photo’s description
  28. echo“<p>$photo[description]</p>”;
  29. ?>
  30. </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).

  1. <div id=“context”>
  2. <?php
  3. // if there is a previous photo…
  4. 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>”;
  5. } else {
  6. // if not - show the blank filler image
  7. echo“<img src=\”noimg.png\” width=\”75\” height=\”75\” alt=\”No photo\” />”;
  8. };
  9. // if there is a next photo…
  10. 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>”;
  11. } else {
  12. // if not - show the blank filler image
  13. echo“<img src=\”noimg.png\” width=\”75\” height=\”75\” alt=\”No photo\” />”;
  14. };
  15. echo“</div>”;
  16. echo“<p>”;
  17. // if there is a previous link, write a link - if not, just the text
  18. if($context[‘prevphoto’][‘id’]){echo“<a  href=\”?id=”.$context[‘prevphoto’][‘id’].“\” title=\”Prev:  “.$context[‘prevphoto’][‘title’].“\”>&laquo; Prev</a>”;} else {echo“&laquo; Prev”;};
  19. echo“ | “;
  20. // if there is a next link, write a link - if not, just the text
  21. if($context[‘nextphoto’][‘id’]){echo“<a  href=\”?id=”.$context[‘nextphoto’][‘id’].“\” title=\”Next:  “.$context[‘nextphoto’][‘title’].“\”>Next  &raquo;</a>”;}else {echo“Next &raquo;”;};
  22. echo“</p>”;
  23. ?>
  24. </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.

  1. <p>&laquo; <a href=“/”>Main gallery</a></p>
  2. <!– To abide by Flickr’s terms - you must include this text –>
  3. <p>This product uses the Flickr API but is not endorsed or certified by Flickr.</p>
  4. </body>
  5. </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.

  1. <?php
  2. } // end if for owner
  3. ?>

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.


  • 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 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: 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: for more tips and advice on taking things further

Posted in programming, Tips n Trik |

1 thought on “Create Photo Gallery using Flickr API

  1. Nice try, but this tutorial isn’t very good.

    Besides that, all your pop-ups and spyware help me to assure you that I will never visit your site again.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: