Displaying a random image using PHP

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:

$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:

<? 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.

6 replies
  1. Lyndi
    Lyndi says:

    A good idea. It could also be changed a little bit to select images that were stored in the database e.g. you could create a separate link category, attach graphics to the items added to this category and then select from these images at random.

    This idea is good, it gives us more choices, but still we have the problem of the server side code not being called if a page is served from cache. I am still too inexperienced with Javascript but if we could code this idea of yours in JS we would have a far better solution than my original idea. We could then have a situation where we do not have to hard code the details of the graphic, and it would work even if the page was served from cache.

    As soon as I have a bit of time I am definitely going to play with this some more. I am going to ‘steal’ your idea and try to get it to work in JS.

  2. Jim
    Jim says:

    Mmm, I was going to reply that you can’t do this in javascript, as the script needs to read the file data from the server, and javascript is client side.

    But, that got me thinking, how’s about taking the filenames as an array in PHP and using PHP to build the javascript? The cache issues would also be avoided, as the content of the array would only change when the directory is updated?

    I don’t currently have a requirement for such a script, so I doubt I will take this further myself, but it is certainly something to keep in mind if you really do need it server from cache.

  3. Lyndi
    Lyndi says:

    Two good ideas here. Firstly using PHP to create the JS and then of course the whole idea of an array. Many WordPress blogs are using the caching plugin and it is definitely something to keep in mind these days. I will keep you informed if I can come up with anything that actually works alongside caching.

  4. Rarst
    Rarst says:

    Good snippet if images are going to change. For static set of images I am sticiking with my tiny “generate random number and stuck it into URL” approach.

  5. Jim
    Jim says:

    @Rarst: Yup, your way is simpler for sure, and I would probably do the same. The way I did it works for those situations where you want to grab from a load of images you don’t pre-name for the script i.e. if you don’t have control over the filenames.

    Like all these solutions, sometimes the simpler ways are the best, but like Lyndi said, there’s more than one way to skin a cat 😀

    Thanks for the comment 😀


Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *