Home Page

Articles

Links Pages

PHP Display A Random Image - Get a Random File Using PHP

This script allows you to display a file at random. It can be used for any type of file, an image or video or text.

You will have to name the page containing this script to end '.php'.

In this example it is used to display a random image every time the page is refreshed.

First name your files consecutively.
Eg., image1.gif, image2.gif, image3.gif, image4.gif, image5.gif.

This section of script below will develop a random filename and store the value in the variable $randomfilename. Place the script near the top of your page above where you need to call the random file.

<?php

$no = (rand()%5);
$no++;
$randomfilename = "image".$no.".gif";

?>

The first two lines of the script create a number between 1 and 5 and store it in the variable $no. If you have more or less files in use just adjust the number 5 to the number of files.

The third line develops the filename by concatenating (sticking together) the first part of the filename "image" with the random number $no and then the filetype suffix ".gif". The filename is stored in the variable $randomfilename.

Now drop the filename into your HTML code to display the random picture.

<p><img src="pics/<?php echo"$randomfilename"; ?>"></p>

 

Refresh and get a new random image

 

To use this script to display different types of files adjust the line

$randomfilename = "image".$no.".gif";

To display a list of videos for instance, video1.mov, video2.mov, etc. change this line to

$randomfilename = "video".$no.".mov";

 

Looking for computer spare parts?
UK Computer Brokers  Datahound Ltd. supply new, refurbished and second user computer spare parts and systems, printers and networking equipment and legacy spares. We also buy back excess computer hardware, business telephones and telephone systems. Corporate computer IT disposals.