Mastering the Flickr API with PHP and cURL

The Flickr API is a very powerful and easy to use way to put photos on your website without having to worry about bandwidth or server performance issues. This tutorial will cover how to make an API call for a photoset and then format and display a list of ~100px thumbnail images in unordered list.

Getting An API Key

To get started with the Flickr API, you need to sign into Flickr and Apply for an API key. After you register for the API Key, you should browse through Flickr’s API page to see some examples of what is possible. As you will see, there are quite a few methods listed which might seem a bit daunting. The nice thing is all of the provided methods are well documented and after one successful implementation, working through the rest is fairly repetitious.

Hot, Steamy PHP Action

We will be using cURL to get the data from Flickr. Some might prefer another method such as PHP’s file_get_contents, there are advantages to both but you can read a book (or Google) for more information on this.

Getting started with the cURL request:

$params = array(
	'method'	=> 'flickr.photosets.getPhotos',
	'photoset_id'	=> '72157622566216264',
	'extras'	=> 'original_format',
	'format'	=> 'php_serial'
$encoded_params = array();
foreach ($params as $k => $v){ $encoded_params[] = urlencode($k).'='.urlencode($v); }

In the code above we first put the API key and then choose the Method (which is listed on the Flickr API page link listed earlier in the tutorial). Next we specify the photo set id which for this example is the set seen in my Portfolio. The parameters for “Extras” depend on the Method used and desired options and range from date uploaded to author to tags. For this example we will be calling “original_format” which will pull a link to the full size version of the image. Finally, we choose “php_serial” as the format which will return a serialized PHP string with the data (Alternatively you could use JSON but we can save that fun for a JavaScript tutorial).

Please note: to use the “original_format” parameter you will need to be a Flickr Pro member.

$ch = curl_init();
$timeout = 5; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, ''.implode('&', $encoded_params));
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);

 $rsp_obj = unserialize($file_contents);

The code above makes the cURL call to Flickr’s API with the data we set in the previous code block, unserializes the cURL object’s returned data and creates a new Array called $rsp_obj.

Let’s pause and take a look at some of the data that was returned with a little print_r($_rsp_ojb) action:

    [photoset] => Array
            [id] => 72157622566216264
            [primary] => 4003748546
            [owner] => 7332638@N08
            [ownername] => benlister
            [photo] => Array
                    [0] => Array
                            [id] => 4003748546
                            [secret] => 69b188c174
                            [server] => 2643
                            [farm] => 3
                            [title] => Chicago (Montrose Harbor)
                            [isprimary] => 1
                            [originalsecret] => 728e01b6c1
                            [originalformat] => jpg

                    [1] => Array
                            [id] => 4052220478
                            [secret] => ec5e79cbbe
                            [server] => 2780
                            [farm] => 3
                            [title] => Seattle Sci-Fi Museum Exterior
                            [isprimary] => 0
                            [originalsecret] => 625519fc32
                            [originalformat] => jpg


The array output above tells us pretty everything we will need to create links to all sizes of each photo in the set. To display each photo in the photo set we first need to step into the [photo] section of the [photoset] array.

if ($rsp_obj['stat'] == 'ok') {

		$photos = $rsp_obj["photoset"]["photo"];

	echo "<ul>";
	foreach($photos as $photo) {

               $farm              = $photo['farm'];
               $server            = $photo['server'];
               $photo_id          = $photo['id'];
               $secret            = $photo['secret'];
               $photo_title       = $photo['title'];

	<li><img /*SEE CODE BLOCK BELOW/* /></li>
	  echo "</li></ul>";
	} else {
            echo "Error getting photos";

[note: the codeblock is not displaying the following img src line correctly in the line above so it has been moved below]

src="http://farm'.$photo['farm'].''.$photo['server'].'/'.$photo['id'].'_'.$photo['secret'].'_t.jpg" alt="'.$photo['title'].'"

The code above first checks to see if the data was returned ok before trying to iterate through the array. Once we have verified that we have the data, we name the [photo] array more intuitively.

Putting it all together

Let’s break down the URL piece by piece to better understand whats going on: For example if the URL is as follows:

  • $photo["farm"] = 3
  • $photo["server"] = 2421
  • $photo["id"] = 4002906997
  • $photo["secret"] = 5e9de854c6
  • _s = 75px square thumbnail
  • _t = 100px thumbnail
  • _m = 240px thumbnail

To get the “normal” 500px image, use the sequence above minus the “underscore letter” ending.

To get the full “original size” takes a bit more work:


UPDATE 7/10: I realized that I haven’t updated this in a while and wanted to share a much easier way to get the original full-size image:

	// In the params array, replace: 	
	'extras'	=> 'original_format',
	// With: 
	'extras'	=> 'url_o',
	//And to call the image:

You should now be able to create a sample image page from a photo set in all sizes. You can also apply these principles to almost any of Flickr’s API Methods to achieve more customized results. Enjoy!

View thumbnail Sample Page

9 comments on “Mastering the Flickr API with PHP and cURL

  1. Forgive me if I’m just missing something, but how do the parameters become “encoded_params” in your example? I’m not a big PHP person, so I’m not sure what I’d use to normalize these params before concatenation to the URL.


    • Doug,

      Sorry for the delay in response and confusion:

      I actually was missing a line in that code block where the urlencode is used on the $params variable.

      $encoded_params = array(); should be proceeded by:

      foreach ($params as $k => $v){ $encoded_params[] = urlencode($k).’=’.urlencode($v); }

  2. Hi,

    I’ve just been following your tutorial above, but can’t get it to work. I’ve changed the API to my own (a non-pro Flickr account), and copied the src= code block in, but (running on Xampp if it makes any difference) get a parse error..

    Parse error: syntax error, unexpected ‘<' in F:\xampp\htdocs\myfile.php on line 50

    Do you know how to fix this? I can't see where the error is!

    Any help greatly appreciated.

    p.s. Shouldn't it be
    $photo_title = $photo['title']; rather than $photo_title = $photo['secret']; ?

  3. Hi, I hope you may be able to help..

    I’ve followed the tutorial through but can’t get it working.. I’ve put my (non-pro account) API key into the code, moved the img src code into the right place but when I try loading it on my local xampp server I get an error..

    Parse error: syntax error, unexpected ‘<' in K:\xampp\htdocs\darkcrimson.php on line 47

    where line 47 is

    Can you / someone spot what is wrong?

    I’d love this to work! Looks spot on for what I want to do and you code was fairly easy to follow.. I thought! :-)

    Any help would be great, thanks

    • Hi David, I responded to your email a moment ago but to share the answer publicly, it appears there was an extra comma at the end of the $params that could potentially cause an error in certain versions of PHP. I’ve also updated the tutorial to reflect this fix.

  4. It seems like the ‘extras’ => ‘url_o’ isn’t working anymore with Flickr, i’ve been trying to get at the original image, but my arrays don’t have that info. You’re demo is also broken.

    Maybe this is something that Flickr has recently changed?

    I can’t find any other info other than what the API says.


    • Hey Dave,

      I recently updated the demo and it looks like I made a typo by adding an extra http:// in the url_o link (it’s fixed now).

      To answer your question, I am almost positive that you need a flickr pro account to use url_o. This is because Flickr for some reason limits the ability to pull the original full sized image for regular users. If you do have a pro account and are still having issues, feel free to email me and I will gladly try to help you out.

    • Thanks for the snappy response Ben! The demo is sharp and this tutorial is great. You from Chicago?

      I found the problem, even though I have a Pro account I still needed to change the Privacy and Permission settings for the original images. “Who can access your original image files?” Ahh! What a relief… it was making my head hurt!

      Kind regards,

  5. How would i edit this code so that instead of looking through a user’s page it searches the site?