<?php /**/ ?><?php
header("Content-Type:text/html");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
    <title>flickrsearch3.php</title>
  </head>
  <body>
<?php
if (isset($_GET['tag'])) {
   do_search($_GET['tag']);
} else {
?>
     <form action="<?php echo $_SERVER['PHP_SELF']?>" method="get">
      Search for photos with the following tag:
    <input type="text" size="20" name="tag"> <input type="submit" value="Go!">
     </form>
<?php
}
?>
<?php

function getResource($url){
  $chandle = curl_init();
  curl_setopt($chandle, CURLOPT_URL, $url);
  curl_setopt($chandle, CURLOPT_RETURNTRANSFER, 1);
  $result = curl_exec($chandle);
  curl_close($chandle);

  return $result;
}

function do_search($tag) {
  $tag = urlencode($tag);
  $url = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=e81ef8102a5160154ef4662adcc9046b&tags={$tag}&per_page=5";

  $feed = getResource($url);
  $xml = simplexml_load_string($feed);
  #print_r($xml);
  #var_dump($xml);
  echo "Total number of photos for {$tag}: ", $xml->photos['total'], "<br>";

# http://www.flickr.com/services/api/misc.urls.html
# http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}.jpg
foreach ($xml->photos->photo as $photo) {
  $title = $photo['title'];
  $farmid = $photo['farm'];
  $serverid = $photo['server'];
  $id = $photo['id'];
  $secret = $photo['secret'];
  $owner = $photo['owner'];
  $thumb_url = "http://farm{$farmid}.static.flickr.com/{$serverid}/{$id}_{$secret}_t.jpg";
  $page_url = "http://www.flickr.com/photos/{$owner}/{$id}";
  $image_html= "<a href='{$page_url}'><img alt='{$title}' src='{$thumb_url}'></a>";
  echo $image_html,"<br>";
}

} # do_search
?>
  </body>
</html>
