Display a Random Image Using PHP

On this page we present a simple PHP script that displays an image selected at random from a directory listing.

Your setup tasks are easy: decide where you want the random image to display, and tell the code where to find your images. The download file includes an example. Instructions and information about the script are provided below.


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, as demonstrated here:

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

A linked image may be displayed with a border in some browsers unless you include the following in the style sheet:

a img { border:none; }

Set the $root and $path variables so the code can find your images. If your images are in a directory under the document displaying them, the variables would be set as follows:

$root = '';
$path = 'images/';

If you are specifying the path to your images from the root, use the following approach:

$path = '/images/rotate/';

The Functions

Only two short functions are required for the script. The first function, getImagesFromDir, obtains a list of images from the directory you specify. The second function, getRandomFromArray, selects an entry from this list at random. The script uses these functions as demonstrated here to select a random image:

$imgList = getImagesFromDir($root . $path);
$img = getRandomFromArray($imgList);

The functions are displayed here:

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) {
    $num = array_rand($ar);
    return $ar[$num];

Download Code - It's Free!

A download file includes the script and an example. See also a simple JavaScript that displays an image selected at random from a list you provide.