Easy Random Image
Yes, truly, this is easy.
-
Upload the
EasyRandomImage.phpscript into a directory that contains images. -
Use the script's URL as the
srcvalue of animgimage tag.
When the web page loads, EasyRandomImage.php selects an image at random and sends it to the img tag.
Of course, the directory where EasyRandomImage.php resides should contain images that are okay to show on your web page. The script may select any PNG, JPG, JPEG, or GIF image in the directory.
The EasyRandomImage.php script is copy and paste. Here is the source code.
<?php /*
Random Image Picker
Version 1.0
December 20, 2025
Will Bontrager Software LLC
https://www.willmaster.com/
How-to:
Put this script into a directory
with images and use the script's
URL as an IMG tag's SRC value.
Only PNG, JPG, JPEG, and GIF
images are recognized.
*/
$images = array();
$selected = '';
foreach(glob('*') as $f){if(is_file($f) and preg_match('/\.(png|jpg|jpeg|gif)$/i',$f)){$images[]=$f;}}
if( count($images)>1 ) { $selected = $images[mt_rand(0,(count($images)-1))]; }
elseif( count($images)==1 ) { $selected = $images[0]; }
if( ! $selected ) { exit; }
$ta = explode('.',$selected);
$ext = strtolower($ta[(count($ta)-1)]);
if($ext=='jpg') { $ext='jpeg'; }
header("Content-type: image/$ext");
readfile($selected);
exit;
?>
Here is an example image tag.
<img src="https://example.com/visuals/EasyRandomImage.php" style="max-width:100%;" alt="random">
Replace the https://example.com/visuals/EasyRandomImage.php URL in the src attribute with the URL to your location of the EasyRandomImage.php script.
If your images are various sizes, and especially if any are oversized, the CSS max-width:100%; declaration that you see in the example img tag can prevent images from trying to take up more room than is available.
Update the style attribute as is appropriate for your installation. Also, the alt attribute may be updated.
This really is an easy way to implement random image selection.
The directory with the EasyRandomImage.php script contains the images that may be selected. The img tag on a web page tells EasyRandomImage.php to randomly pick one of the images in the directory.
(This content first appeared in Possibilities newsletter.)
Will Bontrager

