blog icon

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:

  1.  
  2. <?php
  3. // everytime you change something in your images folder you have to update the $totalImgs variable with the new number of total images.
  4. $totalImgs = 5;
  5.  
  6. // generate a random number between 1 and, in this case, 5
  7. $imgNum = rand(1,$totalImgs);
  8.  
  9. //construct the image url path
  10. $imgURL = ‘./images/img’.$imgNum.‘.jpg’;
  11. ?>
  12.  
  13. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  14.  
  15. <html lang="en">
  16. <head>
  17.         <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  18.         <title>Random Image using PHP</title>
  19.        
  20.         <style type="text/css">
  21.         #header { margin:auto; width:400px; height:200px; border:5px solid #000000;}
  22.         </style>
  23. </head>
  24. <body>
  25.  
  26. <div id="header">
  27. <?php
  28. // echo the img HTML using the image path var ($imgURL)
  29. echo "<img src=’".$imgURL." />";
  30. ?>
  31. </div>
  32.  
  33. </body>
  34. </html>
  35.  

You can see this example here.

That’s it!

Filed under: Blog, Tutorials

Comments are closed.