The solution relied on the image names being hard coded into the script. I thought it would be quite cool to come up with a solution that simply looked in a directory for all the JPG’s or GIF’s, and plucked one at random.
This is what I came up with:
$dir = “images”; // The directory where your images are
$filetypes = (“jpg”||”gif”); // Whatever images are valid. You could add “png” etc
srand((double)microtime()*123456789); // Generates a random number seed
$count = 0; // Initialises the counter
$dirOpen = opendir($dir); // Opens the image directory
while(($im = readdir($dirOpen)))
if($im != “..” && $im != “.” && substr($im,-3)==$filetypes) // Disregards “..” and “.” (direcrory structure)
$image[$count] = $im; // Reads an image
$count++; // Increments the counter
closedir($dirOpen); // Closes the directory
$randname = rand(0,(count($image)-1)); // Generates the random number
echo ‘<img src=”‘.$dir.’/’.$image[$randname].'” alt=”Random Image” />’; // Publishes the image
I have commented the code, so it should be fairly self-explanatory how it works.
It is a bit rough and ready, but it does the job. To implement this on a website, simply use:
The beauty of this solution is you can add as many images as you like to the images (or whatever you call it) folder. Add and remove them at will and the script just picks from the images that are there at the time.
Let me know what you think.