Exercise : Animal Gallery (by Alex Miller)

Given a directory of animal pictures (images.zip), write a PHP webpage animals.php which displays these pictures.

If no query parameter is set, then the page should simply display all of the images in the images directory. The user can set an animal query parameter to choose whether to display only puppy pictures, only pony pictures, or only kitty pictures. For example, if the user entered the following URL:

animals.php?animal=puppy

Then the page should only display puppy pictures. The animal parameters that do have photos are kitty, puppy and pony If the user types in a different query parameter that does not have any photos, you should display a message saying that there are no photos for that animal.

Exercise Solution

<!DOCTYPE html PUBLIC>
<html>
  <head>
     <title>Animal Gallery</title>
  </head>
  <body>
    <div>
      <?php
      $animal = "";
      if (isset($_GET["animal"])) {
          $animal = $_GET["animal"];
      }
      $files = glob("images/{$animal}*.jpeg");
      if(count($files) == 0) {?>
         <p> Sorry, looks like we don't have any photos of <?= $animal ?>s.</p>
      <?php } else {
         foreach ($files as $image) {
            ?>
            <img src="<?= $image ?>" alt="animal picture" />
            <?php
         }
      }
      ?>
    </div>
  </body>
</html>