Random Image

Having images change on your web site is a slick way to give the impression of freshness to your site for a returning visitor.

This simple PHP script will display a random image from all the images available to it.

Reload this page to see the random image changer in action.

Using this script on your site.

I use simple scripts like this as custom functions included in the head of my web page. Then, I can call the function without a lot of extra markup involved. Keeps my pages leaner and cleaner.

So, for this example, I would save the php code as a page called 'randomImage.inc.php' and put it in a folder I call 'includes'.

Remember, you'll have to save your web page with the '.php' extension to get the script to work!

PHP code for Random Image function

<?php
// function to display a random image

function randomImage() {

$images = array(
0 => 'alone_01.jpg',
1 => 'broken_glass_01.jpg',
2 => 'bug_01.jpg',
3 => 'cups_01.jpg',
4 => 'girl_01.jpg',
5 => 'kid_01.jpg',
6 => 'matches_01.jpg',
7 => 'skating_01.jpg',
8 => 'street_art_01.jpg',
9 => 'sunset_01.jpg');

srand ((double) microtime() * 1000000);
$random_number = rand(0,count($images)-1);

$image = ($images[$random_number]);
return $image;
}

HTML for Random image function

<?php
include 'includes/randomImage.inc.php';
?>
<html>
<body>

<p>Lorem ipsum qui.....</p>
<img src="images/<?php echo randomImage();?>" />

<body>
<html>

I also have a random text script and random quote script as well.