Random Image using PHP
Ok… this is really going to be simple.
You want to display a random image inside, lets say, a header div.
For the sake of simplicity, put all the images you want to display inside a folder and name them something1.jpg (or png, or gif, or whatever), something2.jpg, something3.jpg, etc…
Now you only have to generate a random number using the php rand() function. This function may receive two parameters: a minimum value and a maximum.
Example: rand(1,30) will return a number between 1 and 30 (inclusive).
In this example I have only 5 images inside a “images” folder. They are named “img1.jpg”, “img2.jpg”, etc…
Here’s the index.php file:
-
-
<?php
-
// everytime you change something in your images folder you have to update the $totalImgs variable with the new number of total images.
-
$totalImgs = 5;
-
-
// generate a random number between 1 and, in this case, 5
-
-
//construct the image url path
-
$imgURL = ‘./images/img’.$imgNum.‘.jpg’;
-
?>
-
-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-
-
<html lang="en">
-
<head>
-
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
-
<title>Random Image using PHP</title>
-
-
<style type="text/css">
-
#header { margin:auto; width:400px; height:200px; border:5px solid #000000;}
-
</style>
-
</head>
-
<body>
-
-
<div id="header">
-
<?php
-
// echo the img HTML using the image path var ($imgURL)
-
?>
-
</div>
-
-
</body>
-
</html>
-
You can see this example here.
That’s it!






