searching and returning images from flickr

posted by ian grant on February 5, 2006 at 4:45 pm | in digital art hacks, telematics, web 2.0 |

A number of people need to get searching flickr, returning and displaying images according to tag or full-text searches and handling associated tags. Although it seems a long process, this tutorial demonstrates one way to approach flickr that is simple and flexible. With application and extension, you can use the contents here to play a part in projects that:

- utilise user input to get images from flickr. ‘User input’ could come from web forms or, like ‘Play Flickr’, from mobile phone SMS messages.
- search and display flickr images from script-based lists of words and associations. Select search terms by semantic analysis (meaning) or other random principles. You could use ‘get related tag functions’ as demonstrating in phpFlickr_search_002_red.php.
- store image search result data in a mysql database or in a text file to use in flash

This tutorial requires:
PHP 4 (or higher), phpFlickr (a library available from http://www.phpflickr.com/)
Optionally Uses:
A mysql database to speed up server responses by using a ‘cache’ or a file system cache (a plain text document)
Basic Requirements: server access with php; free flickr account and flickr API key; ftp program, a good text editor or dreamweaver 20mins.

Instead of getting down and dirty with flickr’s own api directly, phpFlickr is a class written by Dan Coulter that hides most of the complexity and, through simple examples, allows elaborate interactions with flickr. There are easy to adapt examples on his website and the documentation is great (see: http://www.phpflickr.com/docs/)

A number of projects I’ve seen depend on returning images from flickr after searching for a keyword, a tag, a cluster name etc… In this example the search term (red, summer, winter) is hard coded into the php. You could supply these terms in many ways. A future tutorial will demonstrate using an array of search terms.

Click below to see what the demo files we are looking at produce:

Link: phpFlickr_search_001.php
Link: phpFlickr_search_002_red.php

Download the source files: phpFlickr_Tutorial_Files_001.zip

Before you get going, there are several basics to get started:

First Steps

(1) Sign up for a free flickr account (http://www.flickr.com)
(2) Get a flickr API key associated with that account (http://www.flickr.com/services/api/key.gne)
Flickr Api Key
image: get a flickr api key after setting up a free account.

(3) download phpFlickr (http://www.phpflickr.com/) and upload it to a directory on a php enabled webserver (eg. zappa.tvu.ac.uk)

Important Note:
Copying and pasting the coloured code may not work. Wordpress and the colour syntax highlighter occasionally messes up some of the characters particularly some angle brackets (>). So: -> becomes -/> and that breaks the php. Download the zipped files and use the coloured code as a broad indication of the scripts flow. You will need to edit the code to get things working. Details below.

You will make reference to a ‘magic’ file (phpFlickr.php) in that directory in any script you write where you wish to use flickr resources in your web pages. eg. This code ‘includes’ the functionality in any page you write:


[php]< ?php
require_once("phpFlickr/phpFlickr.php"); // the path to the file must be accurate
?>
[/php]

Including this file does a lot of the work for you, you just then have to learn how to use the function calls and how to do with the results the calls ‘return’. Although this looks complicated, desconstructing the sample code is relatively simple.

Here is an example php script, adapted from an example on the phpflickr page that uses phpFlickr to search for images sorted by ‘interestingness’ - a useful category for returning pictures selected using flickr’s own sorting algorithms


require_once("phpFlickr/phpFlickr.php");
// Create new phpFlickr object
$flickr_object = new phpFlickr("[insert your flickr api key]");
// Enable transparent caching.
$flickr_object->enableCache(
“db”,
“mysql://root:torme@localhost/phpflickr_cache”
);

echo “

Most interesting photos tagged with \”red\”:
\n”;
// Search by the single tag “red”
$photos_red = $flickr_object->photos_search(array(”tags”=>”red”, “sort”=>”interestingness-desc”, “per_page”=>6));
foreach ($photos_red['photo'] as $photo) {
// Build image and link tags for each photo tagged with ‘red’
echo ““;
echo “$photo[title] "src=" . $flickr_object-/>buildPhotoURL($photo, “Square”) . “>”;
echo “
“;
}
echo “

\n”;

?>

file: phpFlickr_search_002_red.php

Step by Step Walkthrough
(1) and (23) Open and closing php tags.

(2) require_once includes the phpFlickr library. We do not need to touch (or understand) the contents of this referenced file. That said, take a look inside the file and you will find better documentation for each function.

The url needs to point to the correct place though. If you do look in phpFlickr.php you will find definitions of all the classes and functions available for playing with flickr. It does a lot more than this example. Note that you pass in the flickr API key. I have taken mine out. You paste yours in this space.

(4) Create a flickr ‘object’ and assign it to a variable. Doing things with (technically ’sending messages to’) ‘$flickr_object’ will achieve the responses we need. An example of such a message is seen in line 12.

(6-9) An optional block that enables great speed enhancements. To take advantages of this you need access to a mysql database. If you have such access the only details you are likely to need to change are as indicated: mysql user name, password, and database name. When the script first runs it populates the existing database with all the tables and data the script will need the next time it runs. It will then not call to flickr, search and fetch images, rather look in your local database - speeding things up significantly.

Mysql Phpmyadmin
image: using phpMyAdmin to create a database

If you don’t have access to a mysql database, you can change lines 6-9 to:


$flickr_object->enableCache(”fs”, “phpFlickrCache”); // fs stands for file system. phpFlickrCache is a directory with permissions of 777
?>

This will ‘cache’ [store] the flickr data to a flat text file on your webserver. You must set the permissions on the target directory allowing the webserver ‘write access’. Permissions set at 777 is overkill but good for troubleshooting. Use a good ftp program to set permissions on directories or files. More info on phpflickr caching at http://www.phpflickr.com/docs/caching/

Project Directory and Changing Permissions Using and FTP Program
Image: Changing directory permissions using and ftp program

(11) This begins ‘printing’ or echoing html out from php to the web page that the end user eventually sees. There are rules to how this happens. Studying the php manual will help http://uk.php.net/manual/en/function.echo.php. Errors can creep into your php AND in the html. Hence, a familiarity with html is very helpful. There are other ways to do this where the html does not get embedded after an echo command and between quotation marks. Ask me for some tips!

(13) Note the use of variables. This is where our phpflickr ‘object’ is sent a list of messages:
in English -
- go to flickr and search for pictures where the image is tagged ‘red’.
- Sort results by ‘interestingness’ descending (meaning most interesting ones first).
- Send us back six results.
In computer jargon, the ‘list of messages’ is an array of parameters expressed as ‘key-value pairs’: eg. tags => red is a ‘key-value pair’ where ‘tags’ is the key and ‘red’ is the value associated with that key. So we pass messages to the object using an array.

Look up these terms, particularly ‘arrays’ to understand them further. Although you don’t need to understand them to get these examples to work, manipulating arrays is central to getting phpflickr to ‘return’ what you want. The results are sent as an array, technically an array of arrays or an associative array. Don’t get scared but here is an ugly, full example. It should be clear from the data represented here, what may be going on behind the scenes of our little search script.


Array
(
[_name] => photos
[_attributes] => Array
(
[page] => 1
[pages] => 23835
[perpage] => 6
[total] => 143009
)

[_value] =>
[page] => 1
[pages] => 23835
[perpage] => 6
[total] => 143009
[photo] => Array
(
[0] => Array
(
[_name] => photo
[_attributes] => Array
(
[id] => 53363322
[owner] => 93291046@N00
[secret] => 03c1a1c6a2
[server] => 27
[title] => Er-Liao/二寮
[ispublic] => 1
[isfriend] => 0
[isfamily] => 0
)

[_value] =>
[id] => 53363322
[owner] => 93291046@N00
[secret] => 03c1a1c6a2
[server] => 27
[title] => Er-Liao/二寮
[ispublic] => 1
[isfriend] => 0
[isfamily] => 0
)

[1] => Array
(
[_name] => photo
[_attributes] => Array
(
[id] => 57472700
[owner] => 78637845@N00
[secret] => ab2bf469ff
[server] => 24
[title] =>
[ispublic] => 1
[isfriend] => 1
[isfamily] => 1
)

[_value] =>
[id] => 57472700
[owner] => 78637845@N00
[secret] => ab2bf469ff
[server] => 24
[title] =>
[ispublic] => 1
[isfriend] => 1
[isfamily] => 1
)

[2] => Array
(
[_name] => photo
[_attributes] => Array
(
[id] => 30706255
[owner] => 66668382@N00
[secret] => 4a21314a00
[server] => 23
[title] =>
[ispublic] => 1
[isfriend] => 1
[isfamily] => 1
)

[_value] =>
[id] => 30706255
[owner] => 66668382@N00
[secret] => 4a21314a00
[server] => 23
[title] =>
[ispublic] => 1
[isfriend] => 1
[isfamily] => 1
)

[3] => Array
(
[_name] => photo
[_attributes] => Array
(
[id] => 37360829
[owner] => 48819593@N00
[secret] => 5f30fdefd6
[server] => 25
[title] => `Nu York Parallax`
[ispublic] => 1
[isfriend] => 0
[isfamily] => 0
)

[_value] =>
[id] => 37360829
[owner] => 48819593@N00
[secret] => 5f30fdefd6
[server] => 25
[title] => `Nu York Parallax`
[ispublic] => 1
[isfriend] => 0
[isfamily] => 0
)

[4] => Array
(
[_name] => photo
[_attributes] => Array
(
[id] => 23471561
[owner] => 78527758@N00
[secret] => 90486d5d23
[server] => 16
[title] => How can I put into words what I feel?
[ispublic] => 1
[isfriend] => 0
[isfamily] => 0
)

[_value] =>
[id] => 23471561
[owner] => 78527758@N00
[secret] => 90486d5d23
[server] => 16
[title] => How can I put into words what I feel?
[ispublic] => 1
[isfriend] => 0
[isfamily] => 0
)

[5] => Array
(
[_name] => photo
[_attributes] => Array
(
[id] => 36145605
[owner] => 51035555243@N01
[secret] => 1901c66046
[server] => 24
[title] => Mars
[ispublic] => 1
[isfriend] => 1
[isfamily] => 1
)

[_value] =>
[id] => 36145605
[owner] => 51035555243@N01
[secret] => 1901c66046
[server] => 24
[title] => Mars
[ispublic] => 1
[isfriend] => 1
[isfamily] => 1
)

)

)

[See Note 1]
If we increased the images to be returned from 6 to 10, the photo array would contain elements numbered 0-9 rather 0-5. Note other pieces of information contained in the response that could be used to build more queries: eg. page number and total pages, image titles.

See: for more on associative areas http://en.wikipedia.org/wiki/Associative_array

(14-20) Is a control structure (see: http://uk.php.net/manual/en/control-structures.foreach.php) that loops through each result sent back and, using the same method as (11) prints out html containing our search results. In this case, the results are returned as ’square’ thumbnails that are links to the full image on flickr [Note 2].
Check out an image on flickr and investigate the structure of the url. That will help to explain the url construction within the ‘a’ html tag.

To display the thumbnail image we use the html image tag:
some text about our picture /><br />
</code></p>
<p>but the image source is constructed simply by calling the function in the following snippet:</p>
<p><code>$flickr_object->buildPhotoURL($photo,

where $photo is each photo sub-array of the array called photo!! PhpFlickr protects us from this complexity. The function does the tricky business of walking through the array and producing the photo source url from the correct key-value pairs. All behind the scenes!

(21) Closes the open paragraph tag, completing the html code block. Make sure you always construct valid html.

Conclusions
This draws to a close this walkthrough.
We demonstrated how phpFlickr, with the right preparation, can use short, elegant scripts to do complex searching of flickr, array crunching and performance-enhancing caching. We saw easy integration with mysql databases and flat text files. We say the ease with which php can write html out for a web browser.

For the more curious:
(a) take a look at the way the returned data is stored both in the mysql tables (you will need access to phpMyAdmin or another similar tool). How easy would it be to get flash working with this data? How could you use phpFlickr as a bridge between flickr and flash?
(b) Try to use and create arrays of words in php to automatically return images according to those words and, maybe, the associated tags.

Notes
Note 1:
Adding this php snippet after line 13 will print out the array structure - good for debugging and general information.

echo "

\n";
print_r($photos_red);
echo "

“;

Note 2: Looking at the source code of phpFlickr (confirmed by the documentation of the flickr api) one can discover that we could use any of the following image sizes/shapes in this function: square, thumbnail, small, medium, large, or original. Medium is the default size.

no comments yet

TrackBack URI

sorry, the comment form is now closed.

(cc) ian grant some rights reserved