php: Get Random Image

đź“… February 4, 2016
randimgUsing a similar technique as the random text PHP code, here is a simple code snippet that chooses an image file at random and displays it in a browser.

This is useful for randomizing a banner image on a web page. Each time the browser refreshes, a different banner image (should) appear. While the same effect can be performed using JavaScript, what if JavaScript is disabled in the browser?

By moving the code to the server side, a random banner image (or any kind of image) will appear in order to add freshness to a page.



$arrImage = array();
$dir = 'images'; # Directory containing images

# Check if directory exists
if (is_dir($dir))
   # Get all PNG images. Concatenate path.
   $arrImage = glob($dir . '/*.png');

   # Any images found?
   if (count($arrImage) > 0)
       # Display image in HTML
       echo '<p><img src="' . $arrImage[array_rand($arrImage)] . '"></p>';
       echo "<p>No images found in <strong>$dir</strong></p>\n";
 echo "<p>Image directory not found.</p>\n";


How It Works

First, select all images you want, and place them in a dedicated directory. In this case, the directory is named “images.” All images are PNG (with lower-case .png extension), but any image format is fine. Change the pattern to match. We also concatenate a forward slash (/). If this is not to your liking, remove it and append it to images to create images/.

$arrImage is the PHP array that will contain a list of relative paths to the images, and $dir locates the image directory relative to the PHP script. In this case, the images directory is a subdirectory from the script.

To make the script a little more fault-tolerant, we check if the image directory exists using the is_dir() function. If good, then we use the glob() function to get a list of all files with the .png filename extension.

Note that the filename extension is case-sensitive. .PNG and .png are two different things. I would recommend renaming all extensions the same for consistency.

If no files match glob’s search pattern (for example, specifying a match with *.PNG when only *.png files exists), then $arrImage will be empty. A check is performed to find out if count($arrImage) is greater than zero. If so, then at least one image was found. This check allows the page to fail gracefully by displaying a message if no images are found. Optionally, a default image could be specified in its place.

If $arrImage contains one or more image paths, then HTML is echoed to the browser for display. The image is chosen at random by the array_rand() function (the same as with random text). Again, you can change the exact output to meet the needs of your page. This is for demonstration purposes.

If the image directory is absent, then an error message appears in the page. This also allows the page to fail gracefully or provide a way to insert a default image in case something went wrong.

These are basics to make your page feel more dynamic, so experiment and have fun!


, ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: