Display a 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="" />

The image can be linked if you like.

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

In order for the linked image not to be displayed with a border, include the following in the style sheet:

a img { border:none; }

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

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

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;
    return $images;

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

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

If no image is displayed, make adjustments to your $root and $path variable entries. The $root variable will very often be an empty string, unless you are specifying 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.