How To Show Random Images From A Folder

by Ben Sinclair
Webmaster-Resources101.com
Friday, 29th July 2005

Ever wanted to display display a random avatar or banners on your forum or website? Continue reading to find out how to do this... It's too simple! 

The Script

Here's the script. Call it something like images.php:

<?php
Header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
Header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
Header("Pragma: no-cache");
Header("Content-Type: image/gif");
$dir = "Images"; // This is the folder where the images are stored
srand((double)microtime()*1000000);
$i = 0;
$dirHandle = opendir($dir); // Open the images folder
while(($im = readdir($dirHandle)))
{
if($im != ".." &amp;&amp; $im != ".") // Don't read in the 2 folders ".." and "."
{
$image[$i] = $im; // Select an image
$i++;
}
}
closedir($dirHandle); // Close the folder
$n = rand(0,(count($image)-1));
if(!readfile($dir."/".$image[$n])) // Read the image
readfile($dir."error/error.gif"); // If the script can't find the directory, display this image
?>

And now on your page, put this: <img src="http://www.yourdomain.com/images.php" border="0">

And there you have it! It will randomly display any image in the images folder!

Enjoy!


Options:
Printer Friendly

About The Author:

Ben Sinclair is the webmaster of Webmaster-Resources101.com, Webmaster-Forums101.com and DevTutors.com

Developer Categories



Developer Tutorials
ASP
CGI & Perl
CSS
Flash
HTML
Java
JavaScript
MySQL
PHP
Python
XML

Developer Documentation

Developer Tools



Search our Developer Tutorials
  The DevSyndicate Network