Search for photos using PHP and the flickr API

This PHP tutorial will show you how to create a simple PHP class that search the flickr site for some photos. To get the data we use the flickr API to run a simple search and return the results in a serialized array.

We will be using the php function "file_get_contents" to receive the data stream from flickr. The data which we will receive, is a serialized PHP array which means all we need to unserialize the array to work with the data returned. As an alternative we can use a cURL function to get the data, for example if the function "file_get_contents" is not allowed on your web host.

API Authentication

The API methods we use in this tutorial doesn’t require any authentication, but we need to use an API key. Get your API key on the flickr web application site (You need an Yahoo account to login).

request api key

Provide some information about your application:

API application

and obtain your personal flickr API key and secret (We need only the key in this tutorial)

api key and secret

Flickr PHP Class

First we create the class structure for our class, we define a private variable for the "API key", a class constructor and the function that will search later for the images.

class Flickr { 
	private $apiKey = 'YOUR API KEY HERE'; 
 
	public function __construct() {
	} 
 
	public function search($query = null) { 
	} 
}

The API method we will be using is "flickr.photos.search", which has a number of possible parameters. We are able to search by tags, full text, tell the API which user to search for, the minimum date it a photo was uploaded and many more. You can find a list of the parameters in the flickr documentation.

So we’re going to run a full text search and limit the number of results to 50.

 
	public function search($query = null) { 
		$search = 'http://flickr.com/services/rest/?method=flickr.photos.search&api_key=' . $this->apiKey . '&text=' . urlencode($query) . '&per_page=50&format=php_serial';
		$result = file_get_contents($search); 
		$result = unserialize($result); 
	}

Notice at the end of $search we have "format=php_serial" other available response formats are rest, xml-rpc, soap and json.

The data which will be stored in the variable $result is a serialized array, so simply unserialize it and return the data. Find below the complete class code and store the code in a file named "flickr.php"

class Flickr { 
	private $apiKey = 'YOUR API KEY HERE'; 
 
	public function __construct() {
	} 
 
	public function search($query = null) { 
		$search = 'http://flickr.com/services/rest/?method=flickr.photos.search&api_key=' . $this->apiKey . '&text=' . urlencode($query) . '&per_page=50&format=php_serial'; 
		$result = file_get_contents($search); 
		$result = unserialize($result); 
		return $result; 
	} 
}

How-to use our PHP class

Create a new PHP script file and add this code:

require_once('flickr.php'); 
$Flickr = new Flickr; 
$data = $Flickr->search('design inspiration'); 
foreach($data['photos']['photo'] as $photo) { 
	// the image URL becomes somthing like 
	// http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}.jpg  
	echo '<img src="' . 'http://farm' . $photo["farm"] . '.static.flickr.com/' . $photo["server"] . '/' . $photo["id"] . '_' . $photo["secret"] . '.jpg">'; 
}

This file simply includes the flickr class we wrote, creates a new instance of the class, runs a search for "design inspiration" and finally loops through the returned data and sends the output to the browser.

photo result

Comments

  1. Replacing the echo line in the php script with:

    echo '<a href="http://www.flickr.com/photos/' . $photo["owner"] . '/' . $photo["id"] . '/" target="_blank" rel="nofollow"><img  border="0" src="http://farm' . $photo["farm"] . '.static.flickr.com/' . $photo["server"] . '/' . $photo["id"] . '_' . $photo["secret"] . '.jpg" width="150" /></a>';

    will show a smaller image and a link to the flickr page with all the details.

  2. Great post, Flickr has every photo you could ever need

  3. Hello Keith,

    thanks for your suggestion, this tutorial is a small example on what is possible using the flickr API.

    Posting code in commnents is often difficult for WordPress, posting PHP code is possible within the “code” tag, but html needs a special “treatment” :(

  4. Keith,

    just used the tutorial for something new, maybe you should check this page instead of using the image width/height attributes ;)

  5. Thanks! I’ve never played much with the API but the getSize method works nicely. The source and url attributes are helpful too!

  6. Thanks! I used this as part of the search service for nowsup.com

  7. This is great, thanks for the info… and the beauty of it is SIMPLICITY.

    I’ll be creating a few context sensitive photo galleries now :)

  8. great tutorial but i’m getting the 112: Method “xxx” not found
    error message when clearly the flickr.photos.search method exists. am i missing something obvious?

    can anyone help?

    thanks

  9. You used exact the same code as from the tutoial?

  10. yes i used the same code as the tutorial but i included a tags parameter with the url:

    public function search($params = null) {
    	$search = 'http://flickr.com/services/rest/?';		
    	if (empty($params)) $params = array();
    		$params['api_key'] = '7e5e91597a596ae828dbfd7fe52e90a5';
    		$params['method'] = 'flickr.photos.search';
    		$params['format'] = 'php_serial';
     
    		if(empty($params)) $params = array();
    		foreach($params as $var => $val) {
    			$var = urlencode($var);
    			$val = urlencode($val);
    			$search .= '&amp;$var=$val';
    		}
    		$result = file_get_contents($search);

    AND THEN:

    $Flickr = new PhotoSearch;
    $data = $Flickr->search(array('tags' => 'white horses'));
  11. The code looks different from mine :) but should work.
    Debug your URL first with:

    echo $search;

    before you use the file function (paste the URL into your browser)

  12. Incredible, I copied the code and it shows me pictures … so everything is ok, but the problem is that it is not mine.
    Yet I entered my API KEY, I do not understand …
    I did a “echo $photo['secret'];” and the secret is random.
    Please can you help me?
    PS: forgive my English.

  13. Hello Razhen,

    the tutorial is about how-to search in the complete database.
    If you like to search only your own photo’s you need to add some value for the “user_id” (check the manual link above)

  14. Hello,

    Thank you for this great tutorial.

    Actually for getting the small and medium thumbnails of specific images just append “_s” or “_m”
    before adding the “.jpg”

    http://farm7.static.flickr.com/6212/6260200673_da9c826d9d_s.jpg

  15. Thanks for the tip Gerald!

  16. Hello,
    Thank you for this great tutorial.
    i want to ask you how can i get one image at a time (a diaporama)
    thx

  17. What is a diaporama? A kind of slideshow?

  18. yes

  19. That was a short answer :)
    What you need is more than the code from this tutorial.
    My advice is to search some jquery slide show plugin/script first. Try different scripts and if you think that some script works for your with static images, you need to use the code from this tutorial to replace the code for your static images.
    It sounds complicated but If you know how to tweak a slide show is handling this code very easy (maybe I should write a tutorial for this)

  20. i try this tutorial with an other code and it works but when i try it with yours it doesn’t work as i want it give me a liste of images
    her is the tutorial:
    http://www.webdesignbooth.com/create-a-vertical-scrolling-news-ticker-with-jquery-and-jcarousel-lite/

    if you can try to make it work
    thank you and sorry for my bad english

  21. There are much better scripts and plugins, search for “jquery slide show”.
    This one looks good to me: http://slidesjs.com/

    Inside the example you need to replace the static content with the dynamic flickr content

  22. Hi Olaf,
    this is a great tutorial, works perfectly :) even for me being a 1 week old php student. I was wondering if there is any way I could grab the image url, and insert it to another img src on the same website?
    thanks

  23. Hello Agnes, I’m glad that my API tutorial helps.
    What you ask is possible by using some jQuery or Javascript code, but it is this about this article too?

  24. Hi Olaf,
    thanks for getting back to me! already sorted out! again, great article :)

  25. Can anyone tell me how to add photos and search for it in flickr Api without using any pre-methods or libraries

  26. You cam make your own API calls to the documented API URLs. It’s not required to use their classes or libs.

  27. hey can u tell me how could i do that

  28. Actually I don’t understand why you’re asking for a way to use the flickr API without any library, while you don’t have an idea how to write your own scripts for some API system. :)
    Check this basic information about the REST request: http://www.flickr.com/services/api/request.rest.html
    You can use curl functions to send a request to the flickr API system.

  29. Is there a url variable I can pass my $_GET['frob'] value to get my private photos? I can get my photos, even using bakedbean’s tag query (very useful), but it only returns photos marked “public”. I understand there is a way to get photos marked “private”, by sending your api_key, api_secret, and the frob, but I don’t know if there is a url variable for the frob, or if I am supposed to do a new READ authentication. That would stink, because of the callback redirect.

  30. Hi Gergory,

    I found this information in API documentation:

    privacy_filter (Optional)
    Return photos only matching a certain privacy level. This only applies when making an authenticated call to view photos you own. Valid values are:
    1 public photos
    2 private photos visible to friends
    3 private photos visible to family
    4 private photos visible to friends & family
    5 completely private photos

  31. Hi Olaf,

    And thanks for the reply. Since I wrote the above post I have mostly conquered the Flickr API with phpFlickr. I can now write pictures to Flickr, set the permissions I want, or read/set any of the photo attributes:
    [id] => xxxxxxxxxxx
    [owner] => xxxxxxxx@N08
    [secret] => 05de381fcd
    [server] => 8248
    [farm] => 9
    [title] => Key West Lobster
    [ispublic] => 1
    [isfriend] => 0
    [isfamily] => 0

    I can set tags when I write the photo, and retrieve any photo using this little snippet of php code:
    $img = array();
    $imgcount = 0;
    $argArray = array(“user_id”=>”$username”,”tags”=>”$mid”);
    $photoset = $f->photos_search($argArray);

    I dropped my work with the frob, and now I am using oauth. It was a long and painful self-taught lesson figuring out how to use oauth. My web server (shared hosting on GoDaddy) does not have PECL installed. The solution was that fortunately some French person wrote phpFlickr with oauth:
    http://asociaux.fr/post/2012/01/06/Authentification-API-Flickr-Oauth-PHPFlickr

    However, I had to take the phpFlickr 3.1 class and merge it with this new class containing the oauth, because the new one for some reason had stripped out whole sections of the original phpFlickr 3.1. If anyone is interested in getting what I think is a complete phpFlickr with oauth, maybe there is a place where I can post the hybrid file.

  32. Hi Gregory,
    I know I was little bit late :)
    Thanks for sharing your code!

  33. Hi Olaf,

    I was trying with the code thats in the tutorial and it doesnt give the images. Instead it pops up with

    require_once(‘Flickr.php’); $Flickr = new Flickr; $data = $Flickr->search(‘design inspiration’); foreach($data['photos']['photo'] as $photo) { // the image URL becomes somthing like // http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}.jpg echo ”;

    stores the Flickr class in Flickr.php and the other code in Flickr1.php

    Am i missing anything else ??

  34. Hi olaf,

    am sorry that i was like a fool to just copy paste the code and forgot to include the
    It work fine.

    Thanks for the great post.

  35. How can I get the img description?

Because of all the spam attemps I've decided to close the comment form at this time. If you have have any questions or comments please post them by using Google+ or Twitter (the links to my profiles are located at the top of this page).