Random Images – PHP

You can use PHP to display pictures randomly for a designated folder on your server. I often use this for random header images in my designs; very effective and puts a different spin on each page.

How it works

Image files are placed within a specific folder on your website’s server. For example ‘rand-img’ (short for ‘random images’) is a nice short and descriptive name – call it whatever you want. When the page with the random PHP is accessed, an array of all of the files within that folder is put together and a random value called. That value can then be used to call up an image.

The PHP

After you have created a folder, i.e. ‘rand-img’ on your website’s server, add the following to the page that you want your images to appear. Please note:you must save your page with the file extension .php in order for this to work.

Let’s put together the PHP:

<?php
$lot_of_rand_img = array();  /// Start the array
$directory = opendir(“rand-img/”); /// The folder in which you keep your random images.

/// Loop through each file within the designated directory

while($rand_img = readdir($directory))
{
if($rand_img != ‘.’ && $rand_img != ‘..’ && !is_dir($rand_img)) /// Make sure that the file exists
{ array_push($lot_of_rand_img, $rand_img); } /// If it does, add or ‘push’ it in to the image array
}

/// Now that the array containing the list of image files has been constructed,
/// close the connection to the directory and start randomising

closedir($directory);
srand(time());

/// Randomise choose 1 value from the image array
$randomise = (rand()%count($lot_of_rand_img));
$current_img = $lot_of_rand_img[$randomise];

/// Echo the image to the browser

echo ‘<img src=”/rand-img/’.$current_img.'” border=”0″>’;

?>

That’s all.