- Computers & Software»
- Computer How-Tos & Tutorials
Random Image Page Load Using PHP - Web Design PHP
Learn To Build Your Own Website
Load A Random Image on Page Refresh Using PHP
This tutorial will explain how to load a random image from your /img file using simple php scripting. I came across this idea when I was getting ready to nod off into the world of slumber, and had to try it out the next day! I hope this helps some aspiring web developers.
You can view the example page below.
Create a folder for your work...
I have created a folder called "Random Image" and created an index.php within. I have also created a sub directory called "img".
See the screenshot below for more detail.
Create random images within your "img" folder.
In my example I have simply created 10 images all the same size, but with different colours. This is so we can distinguish between the images when we test our script.
The images are all named after numbers 1.jpg to 10.jpg.
See the image below for more detail.
img Folder View
Code to insert into index.php...
The code below must be inserted into the index.php file.
This code can be placed anywhere on your website. However in this example we are simply using index.php as our home page.
See the code below.
PHP and HTML Code
<html> <head> <title>Random Image</title> </head> <body> <? $randomnum1 = rand(1, 3); $randomnum2 = rand(4, 6); $randomnum3 = rand(7, 10); ?> <img src="img/<?php echo $randomnum1; ?>.JPG" /> <img src="img/<?php echo $randomnum2; ?>.JPG" /> <img src="img/<?php echo $randomnum3; ?>.JPG" /> </body> </html>
In the code above I have created 3 variables:
$randomnum1, $randomnum2 and $randomnum3.
I have assigned a random value to each of the variables using the rand function available to us in the php language.
x being our random number range.
Notice how I have only assigned 1 to 3, 4 to 6 and 7 to 10.
This prevents the page from showing the same image twice!
Next we just display our images using the <img src = "" /> HTML syntax.
Instead of actually specifying an image location within the quotation marks for the source, we simply echo the output of the our $randomnum variables. This allows the page to select a number from 1 to 10 and insert that infront of .img.
<img src="img/<?php echo $randomnum1; ?>.JPG" />
<img src="img/<?php echo $randomnum2; ?>.JPG" />
<img src="img/<?php echo $randomnum3; ?>.JPG" />
The php code has been marked in bold for you to see. We have now sucesfully created our page which loads random images each time! You can view an example of the page I created at the following link.
Thanks for reading.
Visit my other pages if you wish.