PHP: How to get a random image to display from a specific folder

So you have a folder full of images, and now you want to display a random image? No problem. There are a few examples you can find around online. However, for alot of the examples, you need to input the set amount of images that are actually in the folder, which can get annoying if you constantly add images or if you just want simplicity for the script to detect how many images are actually in the folder.

If you played with PHP and getting files, you will know that opendir('folder') will do the trick for getting files. But what if there is more then just images in the folder? You don’t want it trying to display .txt file now do you? It simply won’t work! (duh.)

So theres a few options. Normally people can use strpos or a similar function to get all images, which is okay, but you would need to use it multiple times depending on how many extensions you have, such as png, jpg, jpeg, bmp, gif, bmp, etc. This can get rather messy doing it that way. However, you can use regular expressions in PHP, which is a huge benefit for something like this. You can use the following: preg_match("/^.*\.(jpg|bmp|jpeg|png|gif)$/i", filenamehere) which is a nice and simple one liner to get any matches of any images. You can also add more extensions if you with rather easy!

I have made a easy to use function, which only involves you inputting a directory, which is very simple. The directory you input is dependent on where the script is running, so you may need to add ../ to backtrack from the current script if the images are not located in a lower level folder. Here is the function:

/*Example to call: randomimage("images/random");
You do not need a ending trail for directory! */
function randomimage($directory) {
	$total = 0;
	$imagelist = array();
 
	//Grab all files in directory for checking and process
	$dir = opendir ($directory);
	while (false !== ($file = readdir($dir))) {
		if (preg_match("/^.*\.(jpg|bmp|jpeg|png|gif)$/i", $file)) { //Use a regular expressions to get extention. Only process jpg/jpeg/bmp/png/gif files.
			$imagelist[] = $file;
		}
	}
	$random = mt_rand(0, count($imagelist) - 1); //Pick a random number from the max array count.
	return '<img src="'. $directory . "/" . $imagelist[$random] . '">'; //Return HTML with random image link. Can adjust this to your liking.
}

So as the comments state, all you need to do is call it through a PHP echo, like so: and you will get a random image in that specific folder! Furthermore, if you think outside the box of just displaying a random image for your site, you can create some little neat things with this script.. For example, a random dice generator script, or a random number draw.

You can view a random dice script that I’ve created that displays three random dice images for your pleasure which can be found HERE! It simply just calls the function three times, and I’ve placed the 6 images require for ‘dice’ in the images folder. Simple!

Hope this helps!

Share

Related posts:

  1. PHP: GIF animation splitter (Split any GIF animiations – frame by frame properly!)
  2. PHP: Easy to use logging class for your scripts.
  3. PHP: Randomizing a text file using PHP + MYSQL, quickly & efficient

About the Author

I mainly focus on Javascript/PHP/C++/.NET applications for everyday and work. I also am working on a remake of Stellar Frontier, an old 2D top down space battle game with a few fellow programmers.