Dark Crimson - The Blog of Ben Lister

PHP:Mastering the Flickr API with PHP and cURL

posted on Nov 28th, 2009 @ 10 pm  under:  , , , , 2

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(
	'api_key'	=> 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
	'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, 'http://api.flickr.com/services/rest/?'.implode('&', $encoded_params));
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($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:

Array
(
    [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 "
    "; foreach($photos as $photo) { $farm = $photo['farm']; $server = $photo['server']; $photo_id = $photo['id']; $secret = $photo['secret']; $photo_title = $photo['secret'];
  • } echo "
"; } 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'].'.static.flickr.com/'.$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

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

http://farm3.static.flickr.com/2421/4002906997_5e9de854c6_t.jpg

  • $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:


src="http://farm'.$photo['farm'].'.static.flickr.com/'.$photo['server'].'/'.$photo['id'].'_'.$photo['originalsecret'].'_o.jpg"

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

  • Digg
  • DZone
  • Twitter
  • Reddit
  • del.icio.us
  • Facebook
  • Design Float
  • Google Bookmarks
  • Print

2 Comments Add a Comment | trackback

  1. Doug Avery:

    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.

    Thanks!

    • 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); }

Leave a Comment