Advanced Image Rotation

Although my original tutorial on image rotations still works, it’s major flaw is the dependency on the script creator to enter a list of images to rotate. While this is not a problem if you only want to rotate a few images, and don’t intend on adding to it after creation, it will become a chore if it’s an ever-updated thing.

The solution to this problem is to create a directory for your images, and use a built in PHP function called glob() to go through that directory and pick up the images for rotation. That way, when you wish to add new images to the rotation it’s as simple as uploading them to the correct directory.

glob() reads the contents of a directory into an array, based on a given pattern. As we’re creating an image rotator, it is likely that we’ll want to pick up any images in our directory with a file extension of .jpg, .gif or .png. We can use the wildcard operator to find all files of these types and put them in our array, using the “GLOB_BRACE” flag to match all 3 possibilities, like so:

$files = glob('{directory/*.png,directory/*.gif,directory/*.jpg}', GLOB_BRACE);

The next step is to simply create a random number using PHP, match it to a key in the array and echo the array value (the image). Because array keys start from 0 (so an array with 10 entries will have the keys 0 through to 9) it is important that when we calculate the maximum random number we can have, we take 1 off to match key value. The full code:

$files = glob('{directory/*.png,directory/*.gif,directory/*.jpg}', GLOB_BRACE);
$image = rand(0, (count($files) - 1));
echo '<img src="'.$files[$image].'" alt="random image" />';

Note: the file path is included in the glob() result array, so you do not need to specify “directory/” in the image path.

Speak Your Mind

*