henry.jarske.net

Writings

PHP: How to show random images

If you just want to get your rotating forum signatures going, all you need is one line of code. Might as well go with a more flexible version, though.

The first, quick and lazy option is to use this short bit, which can pick one out of a series of images. Just copy and paste the code to a new file and save it, for example as random.php.

<?php
  header("Location: http://www.example.com/image" . rand(1,5) . ".gif");
?>

All of your files need to be of the same type and renamed to follow a series like image1.gif, image2.gif and so on. Change the URL parts, then the start and end numbers inside rand() to point to your own set of images and you're done.

Another way is to let the code find all your files. If you want to know how the longer script shown below works, keep reading to the end.

To get this next one working, you only need to upload it to the same directory where you keep your images. Type in the script's new address to a browser and refresh the page a few times to see it at work. In HTML, you can now use a normal image tag (<img src="http://www.example.com/random.php">) to include random pictures, signatures images or however you might want use the script.

<?php
  // Configuration
  $image_path = "";
  $types = array(
    "GIF" => "image/gif",
    "JPG" => "image/jpg",
    "PNG" => "image/png");

  // Directory scan
  $file_list = array();
  $image_path = realpath(trim($image_path) != "" ? $image_path : ".") . "/";
  if ($image_path !== false && is_dir($image_path) && $handle = @opendir($image_path))
  {
    while (($file = readdir($handle)) !== false)
    {
      if (is_file($image_path . $file))
      {
        $file_extension = strtoupper(substr(strrchr($file, "."), 1));
        if (isset($types[$file_extension]))
        {
          $file_list[] = array(
            "filename" => $image_path . $file,
            "mimetype" => $types[$file_extension]);
        }
      }
    }
  }

  // Output
  if (sizeof($file_list) > 0)
  {
    shuffle($file_list);
    header("Content-Type: " . $file_list[0]["mimetype"]);
    header("Content-Length: " . @filesize($file_list[0]["filename"]));
    @readfile($file_list[0]["filename"]);
  }
  else
  {
    die("No images found.");
  }
?>

The configuration part looks like this:

Here's how it works:

  1. The given $image_path is checked and converted to an absolute path with a trailing slash.
  2. The directory is scanned for files using the opendir() and readdir() functions.
  3. Each file's extension is checked against the list from $types and only included in the pool of available images if it's a known type.
  4. When all files are added to the $file_list array, it's mixed around with shuffle() to bring a random one on top. This way $file_list[0] always points to a random file.
  5. HTTP headers and the content of the file itself is given to the client.