Display Random Image Using PHP

The code on this page displays an image selected at random using PHP. The list of images for this example comes from a directory listing. You could also select an image from an array of images from other sources, such as a database query, or a static list of images you provide.

The code for this example:

<?php
function getRandomFromArray($ar) {
    
mt_srand( (double)microtime() * 1000000 );
    
$num array_rand($ar);
    return 
$ar[$num];
}

function 
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;
            }
        }
        
closedir($img_dir);
    }
    return 
$images;
}

$root '';
// If images not in sub directory of current directory specify root 
//$root = $_SERVER['DOCUMENT_ROOT'];

$path 'images/';

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

$img getRandomFromArray($imgList);

?>

Place the following where you wish the random image to appear:

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

 

JavaScript Version

See the version that just uses JavaScript to display an image selected at random from the list you provide.