Random Image Script (no database) Tutorial
Made by: Nick
I have been asked by a lot of people how I created the random "featured layout" part of this site and I thought it would be a good idea for me to explain it in a tutorial for anyone else who has wondered but never asked.
This site actually uses a random script using a database (because it's much easier to do the way this site is set up), I will make a tutorial about that later, for now I will make one which will show you how to create a random image script without using a database.
First we need to create our random image function file, call this something like "randomImage.php" and fill it with the following PHP code:
<?php
// function to display a random image
function randomImage() {
$images = array(
0 => '<img src="image1.jpg" alt="image 1" />',
1 => '<img src="image2.jpg" alt="image 2" />',
2 => '<img src="image3.jpg" alt="image 3" />',
3 => '<img src="image4.jpg" alt="image 4" />',
4 => '<img src="image5.jpg" alt="image 5" />'
// add in more images by adding more rows, e.g. 5 => '<img src="image6.jpg" alt="image 6" />'
// Don't forget that you need a comma at the end of each row except the last one.
);
// Generates a random number between 0 and the amount of images that are in the array
$random_number = rand(0,count($images)-1);
// sets $image to the image in the array at the slot of the random number
$image = ($images[$random_number]);
// returns the variable $image
return $image;
}
?>
After this all we need to do is include the file we just created into another php file where you want the random image to be displayed, for example I created a page called "random.php":
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<?php include 'randomImage.php'; ?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Random Image</title>
</head>
<body>
<p>
<?php echo randomImage(); ?>
</p>
</body>
</html>
You can download the source code files below:
random image (rar file)
Enjoy,
Nick