Ade in Business

The enterprising journey of a web developer

Ade in Business header image 1

Batch download Flickr images with PHP

January 17th, 2007 · 1 Comment

cardinal.pngEvery now and then I need a batch of image files to use in testing, and typically go to Flickr or one of the many other photo sharing sites to right-click, “Save Image As…” and download a number of photos. I’m inviting RSI issues if I do that 100s of times, and it’s as boring to use a couple images over and over as it is to pull images off a 10 year old stock photos CD.

So I started playing around with the Flickr API and created the lightweight script below to use to batch download images from the interestingness group. It can be easily modified to download images from other groups, or the site at large, but I chose interestingness because I’d rather look at some cool photos while I debug than group photos from Christmas parties.

  1. #!/usr/bin/php -q
  2. <?php
  3.  
  4. // Replace with your Flickr API key
  5. $key = 'YOURFLICKRAPIKEY';
  6.  
  7. // Parse optional command line arguments:
  8. // flickrdl.php <dest directory> <num images>
  9. // e.g.: flickrdl.php /tmp 25
  10. $dir = $_SERVER['argc'] > 1 ? $_SERVER['argv'][1] : ‘.’;
  11. $num = $_SERVER['argc'] > 2 ? $_SERVER['argv'][2] : 1;
  12.  
  13. // Send an API request to get the image list
  14. $res = file_get_contents("http://api.flickr.com/services/rest/?".
  15. "method=flickr.interestingness.getList".
  16. "&api_key=$key&per_page=$num");
  17.  
  18. // Parse the XML response
  19. $search = new SimpleXMLElement(trim($res));
  20. if ($search['stat'] == ‘fail’) die($search->err[0]['msg']);
  21.  
  22. // Iterate over each photo
  23. foreach ($search->photos[0] as $photo) {
  24.  
  25. // Print photo ID for debugging/notification
  26. print "{$dir}/{$photo['id']}.jpg\n";
  27.  
  28. // Download the image and save to local file
  29. copy("http://static.flickr.com/{$photo['server']}".
  30. "/{$photo['id']}_{$photo['secret']}.jpg",
  31. "{$dir}/{$photo['id']}.jpg");
  32. }
  33.  
  34. ?>
  35.  

To use it you’ll need a Flickr API key which you’ll receive immediately after filling out a simple application. You’ll also need PHP 5 on Unix or Windows. Run the script as-is from a command line to download a single image to the current directory, or with a directory path and number as arguments to change the default behavior. e.g.:

flickrdl.php /tmp 100

Tags: , , ,

1 response so far ↓

  • 1 Raphael // Jan 8, 2008 at 5:07 pm

    Almost what I need.
    But not exactly.

    I was looking for a script that would make an archive out of an album and enable people to download it.

    Kind of proxy for flickr.

    This would be usefull to give a simple URL for friends to donwload our complete album.

Leave a Comment