Simple Random Image With PHP

We’ve already covered ‘creating a random image with JavaScript’ but the best way to produce a random image on each page load is to use PHP. Using PHP, you are not relying on the browser supporting JavaScript at all and everyone will see the random images.

OK, to start, we’ll create a function called randomSelect(). This will take two parameters; the directory to scan for images and an array of the allowed file extensions to use.

function randomSelect($dir,$extensions = array()) {

We create an array($imgs) to hold the images and a variable($files) to reference the files in the directory.

//scan the directory
$files = scandir($dir);
// create an array to hold the images
$imgs = array();

The next block of code runs through each file in the directory. It makes sure the file is a file and not a folder and checks that the filename ends in one of the allowed extensions. If the file passes these two tests, it is added into our $imgs array for later reference.

if ($files) {
    foreach ($files as $file) {
        if ((in_array(substr($file,-4,4), $extensions)) && is_file($file)) {
	    //add the image to the $imgs array
	    $imgs[] .= $file;
	}		
    }

Next, we generate a random image from the $img array

//find a random image
$newrandImg = rand(0, count($imgs) -1);

Although this does indeed generate a random number which we can use to display an image from our array, there is a small problem. The next time the page reloads, a new random image will be generated but it might be the same as the last one! To the site visitor there would be no difference at all. To prevent this, we’re going to store the last image displayed inside a session variable.

//check for existing image
if (isset($_SESSION['randImg'])) {
	$oldrandImg = $_SESSION['randImg'];
} else {
	$oldrandImg = null;
}

We can then compare the last image diplayed to the new random image.

if ($oldrandImg == $newrandImg) {
    //select a new image
    if ($newrandImg < count($imgs)-1 ) {
        // if the last displayed image is not the last one in the array
        // add one to its value and assign the new value to $newrandImg
	$newrandImg += 1;
    } 
    elseif ($newrandImg > 0) {
        // if the last displayed image is not the first one in the array
        // deduct one from its value and assign the new value to $newrandImg
	$newrandImg -= 1;
    }
}

All that’s left is to overwrite the session variable with our $newrandImg value and echo the resulting <img> tag. We also print out a basic error message if $files returned false.

$_SESSION['randImg'] = $newrandImg;
echo '<img src="' . $imgs[$newrandImg] . '" alt="A Random Image" />';
}
else { // if $files doesn't exist
    echo "Couldn't read the file directory";
}

The complete function looks like this:

<?php //rotate and select a random image 
function randomSelect($dir,$extensions = array()) {
	// create an array to hold the images
	$imgs = array();
	//scan the directory
	$files = scandir($dir);
 
	if ($files) {
		foreach ($files as $file) {//loop through the files in the directory
			if ((in_array(substr($file,-4,4), $extensions)) && is_file($file)) {
 
			//add the image to the $imgs array
			$imgs[] .= $file;
			}		
		} 
 
	//find a random image
	$newrandImg = rand(0, count($imgs) -1);
 
	//check for existing image
	if (isset($_SESSION['randImg'])) {
		$oldrandImg = $_SESSION['randImg'];
	} else {
		$oldrandImg = null;
	}
 
	if ($oldrandImg == $newrandImg) {
            //select a new image
		if ($newrandImg < count($imgs)-1 ) {
			$newrandImg += 1;
		} 
		elseif ($newrandImg > 0) {
			$newrandImg -= 1;
		}
	}
	$_SESSION['randImg'] = $newrandImg;
	echo '<img src="' . $imgs[$newrandImg] . '" alt="A Random Image" />';
	}
	else { // if $files doesn't exist
		echo "Couldn't read the file directory";
	}
}
?>

To call this function on a page, you first need to start a session using session_start() and include the php file with the function (for example ‘rotate.php’). Then simply call the function where you like. You can use this on any page on your site that calls session_start() and includes your function file.

<?php
session_start();
include_once('rotate.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<?php randomSelect('phprotateimages',$extensions = array('.jpg','.png'));?>
</body>
</html>

You can see an example here :)

Feed IconFollow me on Twitter





10 Responses to “Simple Random Image With PHP”

  1. Another nice article there mate :)

    Dugg!

  2. Awesome, a simple change and I made it into a rotating ad function :)

  3. Glad you found it useful :)

  4. Really helpfull, but im still a little confused. Quite new to php but, Ive presumed ‘phprotateimages’ your image directory, and ive set mine accordingly.

    However im still not getting any images. Simply the displaying the alt attribute, but NOT the “Couldn’t read the file directory”.

    Can you help?

  5. Hi ALIT,
    So you’re getting ‘A Random Image’ as the alt text?
    Directly after this code in the function:

    echo '<img src="' . $imgs[$newrandImg] . '" alt="A Random Image" />';

    place the following and let me know what it prints out.

    print_r($files);

    It should print out an array of the files in the directory.

  6. Thanks for the help ElanMan. Included that code and get the following

    A Random ImageArray ( [0] => . [1] => .. [2] => 1.jpg [3] => 2.jpg )

    At the moment there are only 2 images in my directory, 1.jpg and 2.jpg. Not sure why the first 2 entries in the array are there however. The directory is simply “images/backgrounds/”. Im using MAMP on a mac.

  7. Hi ALIT, the ‘.’ and ‘..’ simply reference the current directory and the parent directory; we don’t need to worry about them here.
    Check the generated source of the page to see where the image src attribute points to. Also, try giving your images slightly longer names, pic1.jpg’ for example.
    Let me know how you get on :)

  8. I’m getting the same thing. No images, just alt text. The generated image tag is as such:

    Using print_r, I also get a listing of files in the directory.

    Any ideas?

  9. The image tag should read:

  10. Hi Hal, unfortunately, your comments have been buggered up by wordpress (or me). Could you please post them again inside <pre> tags?

Leave a Comment







XHTML: You can use the following tags in your comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">