Lyndi posted about displaying an image at random the other day. Her solution was to use javascript as it enabled the page to do this even if the server had caching on. It was a good solution, but it got me thinking about going in a slightly different direction…
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:
<?php
$dir = “images”; // The directory where your images are
$filetypes = (“jpg”||”gif”); // Whatever images are valid. You could add “png” etcsrand((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:
<? include(‘randimg.php’)?>
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.
I decided a while back that I was going to use this blog as a springboard to try out new technologies and to write about them. I have tried a few and am in the process of experimenting with several others, but I have come to the end of the line with Kontera Affiliates and would like to share my experience.
Recent Comments