Display Random Images with PHP

random image

Images @ Painted Pixels

This is a simple way to display images on your web page using PHP. Each time the page is refreshed, the script will choose one image from a list of images to display on your page.

What you need

Your webserver must be able to run PHP scripts.

Step One

Create your web page as normal but save it with a php extension, for example, randomimage.php.

Step Two

Create a directory for your images and upload your images into that directory.

Step Three

Copy this code and paste it into the top of your web page like this:

<?php
// Random Image Script by www.paintedpixels.com

$url = "www.yoursite.com/randomimage/images/";

$imageArray[0] = "image1.jpg";
$imageArray[1] = "image2.jpg";
$imageArray[2] = "image3.jpg";
$imageArray[3] = "image4.jpg";

$randImg= $imageArray[rand(0, count($imageArray) - 1)];

$imgurl = "http://".$url.$randImg;
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
< html>
< head>

What does it mean?

$url = "www.yoursite.com/randomimage/images/";

This is the url of your web page. Change it to reflect your site structure. Do not put http://

$imageArray[0] = "image1.jpg";
$imageArray[1] = "image2.jpg";
$imageArray[2] = "image3.jpg";
$imageArray[3] = "image4.jpg";

These are your images. Replace "image1.jpg";, "image2.jpg"; etc with the name of your images.

If you wish to add more than four images continue the pattern like this:

$imageArray[4] = "image5.jpg";
$imageArray[5] = "image6.jpg";
$imageArray[6] = "image7.jpg";

Notice how the format stays the same. Only the number in square brackets increases by 1 for each image.

$randImg= $imageArray[rand(0, count($imageArray) - 1)];
$imgurl = "http://".$url.$randImg;

These two lines choose a random image from the array and works out the full url to your image. Do not change these two lines.

Step Four

Decide where you want your image to display on your page and add the following line of code in that place:

<img src="<?php echo $imgurl;?>" alt="random image">

Your page should look similar to this:

<?php
// Random Image Script by www.paintedpixels.com

$url = "www.yoursite.com/randomimage/images/";

$imageArray[0] = "image1.jpg";
$imageArray[1] = "image2.jpg";
$imageArray[2] = "image3.jpg";
$imageArray[3] = "image4.jpg";

$randImg= $imageArray[rand(0, count($imageArray) - 1)];

$imgurl = "http://".$url.$randImg;
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
< html>
< head>
<title>Random Image</title>
< meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
< /head>

<body>
<h2 align="center">My Images</h2>
< p align="center"><img src="<?php echo $imgurl;?>" alt="random image"></p>

</body>
< /html>

Now when you refresh the page, a different image will be displayed. Enjoy!