Displaying a random image using PHP
Ever wanted to show a random image on your website? This short tutorial goes through the simple steps involved to display a simple random image using the popular server-side scripting language; PHP.
There are 2 main ways of displaying a random image. The first is to loop through the images in a defined order each time the page loads (using cookies to store the current image). The second is to display a random image each time the page loads regardless of sequence. This tutorial goes through the code required for the latter and is meant as a quick and easy solution.
In this example we are going to display a random image from a pool of 5 images.
Step 1. Create the images
The images should be named 1 to 5, for example:
- image1.jpg
- image2.jpg
- image3.jpg
- image4.jpg
- image5.jpg
Step 2. The PHP code
Insert the following code into your PHP page:
<?php #generate a random number between 1 and 5 $image = rand(1, 5); #print out the image HTML echo '<img src="image'.$image.'.jpg">'; ?>
All done!
This tutorial has shown a very simple way to display a random image using the PHP rand() function. More advanced techniques can be used, including the use of cookies to prevent the same random image being shown twice.
For more information on any of the code featured above visit www.php.net for the online manual.
