Display Random Image Using PHP

The code on this page uses PHP to display an image selected at random from a directory listing.

The code is brief and simple, requiring only two functions. The first, getImagesFromDir, obtains a list of the images in the directory you specify. The second, getRandomFromArray, selects an entry from this list at random.


Place the following where you wish the random image to appear in your markup:

<img src="<?php echo $path $img ?>" alt="" />

Set the $root and $path variables so the code can find your images:

//$root = $_SERVER['DOCUMENT_ROOT']; // use if specifying path from root
$path 'images/';

getImagesFromDir($path) {
$images = array();
    if ( 
$img_dir = @opendir($path) ) {
        while ( 
false !== ($img_file readdir($img_dir)) ) {
// checks for gif, jpg, png
if ( preg_match("/(\.gif|\.jpg|\.png)$/"$img_file) ) {
$images[] = $img_file;

getRandomFromArray($ar) {
mt_srand( (double)microtime() * 1000000 ); // php 4.2+ not needed
$num array_rand($ar);

// Obtain list of images from directory 
$imgList getImagesFromDir($root $path);
$img getRandomFromArray($imgList);

If no image is displayed, check your $root and $path variable entries. The $root variable may be an empty string, or you may want to specify the path from the server root.

That's all there is to it! An example is provided in a download file. See also the code that uses JavaScript to display an image selected at random from the list you provide.