Welcome to Webmaster Resources 101


Our Network:

How To Show Random Images From A Folder

[ About This Author :: Request Reprint :: Print Article :: Tell A Friend ]

How To Show Random Images From A Folder

By Ben Sinclair
http://www.webmaster-resources101.com

Ever wanted to display display a random avatar or banners on your forum or website? Continue reading to find out how...

<b>The Script</b>

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

<font color="green"><?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

srand((double)microtime()*1000000);
$i = 0;
$dirHandle = opendir($dir); // Open the images folder
while(($im = readdir($dirHandle)))
{
if($im != ".." && $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
?> </font>

And now on your page, put this:

<font color="green"><img src="http://www.yourdomain.com/images.php" border="0"></font>

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

Enjoy!

 
Other Related Material:

Discuss this in our Webmaster Forums

About The Author:
Ben Sinclair
http://www.webmaster-resources101.com
Ben Sinclair is the Webmaster of Webmaster Resources 101 and Webmaster Forums 101.
Go To Top

This article has been read 1091 times.

[ About This Author :: Request Reprint :: Print Article :: Tell A Friend ]