kirkbrown.com

Huh?

Random Image Rotation

without comments

Here’s a quick routine I used a while back to pull a set of images from a directory, and then randomly rotate through them on page load. I thought it was an interesting way to have a changing front page marquee without the annoyance of flash or javascript special effects:

<?php

$imageDirectory = '/path/to/images/';
$imageURL = '/url/to/images/';
$randomImage = $imageURL . randomImage($imageDirectory);

function randomImage($dir) {
  $files = array();
  if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
      while (false !== ($file = readdir($dh))) {
        if ($file != "." && $file != "..") {
          $files[] = $file;
        }
      }
      closedir($dh);
    }
  }
  $totalImages = count($files);
  $maxImages = $totalImages - 1;
  $randomImage = rand(0, $maxImages);
  return $files[$randomImage];
}
?>

<img src="<?= $randomImage ?>" />

I start by creating a directory for storing the images. Since we’re going to be reading the directory contents, there’s no need to worry about any particular naming order or convention other than the ones required by your operating system. If you want to add more images to the rotation later, just place them in this base directory and they will be included immediately. Eliminating hard-coded arrays or lists of images makes it much easier to control this script in the future.

The first thing I do in the script is set up the server path and the URL to my image directory. The path is the physical location on the disk, while the URL is the address you’d type into your browser to view them. These will vary depending on your particular server setup.

$imageDirectory = '/path/to/images/';
$imageURL = '/url/to/images/';

Next I call the random image function with the server path, and store the URL for a random image in the $randomImage variable.

$randomImage = $imageURL . randomImage($imageDirectory);

You can see at the very bottom of the program, I use this variable to output the URL in the src tag of an image. Inside the function, I create an empty array for the results, test to see if the $dir variable is an actual directory, and open it if it is.

$files = array();
if (is_dir($dir)) {
  if ($dh = opendir($dir))

$dh is short for ‘directory handle’, which is the pointer or ‘handle’ to the actual disk resource. The next step is to start up a while loop to read in the contents of the directory.

while (false !== ($file = readdir($dh)))

This will kill the loop when there are no more files to be read and the readdir function gives a false return. There are shorter ways to write this particular statement, but the PHP site recommends this specific usage as the correct one. In this case, the loop will not exit unless the return value of the readdir function is identical to false (meaning equal to and of the same type). For more information, take a look at the not identical operator on the PHP web site.

Next comes one last bit of housecleaning as I strike out any entries that are equal to ’.’ or ’..’. If it’s passed all these tests, it must be one of our images, so I push the filename into the $files array.

if ($file != "." && $file != "..") {
  $files[] = $file;

Finally, there’s a tiny bit of basic math to choose the random image. $totalImages gets the total number of images (or files) in the specified directory by using the count() function. Since the array starts at 0, rather than 1, I need to set an upper limit that is one less than the actual total in the $maxImages variable.

We let the rand() function give us a random number between 0 and $maxImages, and return the random array element that corresponds.

$totalImages = count($files);
$maxImages = $totalImages - 1;
$randomImage = rand(0, $maxImages);
return $files[$randomImage];

And that’s that.

Written by kirk

June 14th, 2006 at 9:22 pm

Posted in PHP

Tagged with

Leave a Reply