Home

Glue Time (PHP Multiple Image Rotator)

by David Pankhurst

Rather than blog chores, it was back to regular work – I’m currently reworking one of my sites, Gift-Cal.com, making it more attractive to visitors (ie. buyers). In line with that, I decided to do a little random image code in PHP to showcase products.

One problem – most rotators are truly random, and if you do more than one image per page, you could get duplicates. I wanted a row of images, and no dups, so I had to roll my own.

Here’s the code for ‘rotate.php’– feel free to customize & plug it into your site (but please keep the copyright in it):

<?php
// rotate images randomly but w/o dups on same page - format:
// <img src='rotate.php?i=0'> - rotate image #0 - use 'i=1'
// for second, etc
//  (c) 2004 David Pankhurst - use freely  but please leave in my credit
$images=array( // list of files to rotate - add as needed
  "img1.gif",
  "img2.gif",
  "img3.gif",
  "img4.gif",
  "" ); // last entry left blank - easier to maintain list this way
$total=count($images)-1;
$secondsFixed=10; // seconds to keep list the same
$seedValue=(int)(time()/$secondsFixed);
srand($seedValue);
for ($i=0;$i<$total;++$i)
{
  $r=rand(0,$total-1);
  $temp =$images[$i];
  $images[$i]=$images[$r];
  $images[$r]=$temp;
}
$index=(int)$_GET['i'];
$i=($seedValue+$index)%$total;
$file=$images[$i];
header("Location: $file");
?>

To use, place your image files into the array (with paths if needed), and use the <img src=’rotate.php?i=0′> invocation on your web pages. Use ?i=1 for the second image on the page, ?i=2 for the third, etc, as needed.

The code doesn’t need any explanation to work – but that won’t stop me. The key is pseudo random numbers. As long as I use the same seed value each time, the function call will return the same randomized sequence. Passing i=0, i=1, etc gets me the appropriately indexed entry from the list. As well, since the list is in turn shuffled, the result is a random, but not repeating, series of images.

(And before I get comments, I wrote my own shuffle because I didn’t like the randomness of PHP’s shuffle() – you can replace it if you wish).

The only other item to note is the $secondsFixed value – I didn’t want the random value changing too often (with time() it would change every second), since that could cause the list to resequence between the first call on the page and the last, resulting in the dreaded repeating images. This factor reduces the chance of that happening, and can be adjusted to suit (it also determines how often the images ’stay’ in their current configuration).

To see it in action, drop by the Gift-Cal.com and check out the top row of images on each page.

Leave a Reply