Tutorial – Pull in a Random Image from a Folder with PHP

I came up with an idea for a client where instead of just pulling in the newest image in a file my code would pull in a random image from a folder. This serves two purposes:
1) Gives visitors the feeling of a page that gets updated and gives them something different to look at when they visit the website again.
2) It also changes the code which shows the page as being updated to spiders and other search engine bots. (To what degree this will help your SEO remains to be seen but likely on par with doing minor updates to your website)

Now how to get this done? Well I looked around and there were a lot of different ways to code it some from using things as simple as echoing an image name with a random number genrator attached to the end of the file name before the extension for example:

To things that would be much more in depth and involved 20+ lines of code. The problem with all the code I found is that they were limited by having to define the file type and/or manually define how many images were in the folder.

Now here’s what I came up with for my random image generator:


That’s all the code I needed… 6 lines of code. This code scans a directory, generates a random number with a maximum set by the amount of files in directory. Then it prints out an image within the defined directory. This allows you to add as many or as few images to the folder as you want without ever changing the code.

Lets break it down:


This first section is doing 2 things:
1) Defines the directory for the images.
2) Creates an array of the defined directory.

Now that we have the files defined in an array lets create a random number generator:

$i = rand(2, sizeof($images)-1);

This line of code is doing 3 things:
1) The obvious part is it generates a random number with rand.
2) We're restricting it to start at 2 because 0 and 1 are always the directories (0 = '.' and 1 = '..')
3) We're restricting the maximum number to the number of the array and subtract 1 from that to account for the fact that the array itself starts at 0, while the code"sizeof()" starts counting with 1 instead of 0.

The last part of the code is what will actually be visible in the HTML/XHTML:

This is spitting out the file name that was randomly picked from the array using the random number we generated.

Update: You could even make the alt tag spit out the name of the file by changing the last line to this:

<?php echo str_replace(array('.jpg', '.png', '.gif'), '', $images[$i]); ?>

This is simply replacing the possible file extensions with nothing so that the alt tag will say "filename" instead of "filename.jpg".

Leave a Reply