Web Development

How to Show Random Images from a Folder

How To Show Random Images From A Folder

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

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

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
?>

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!

About the author

Written by Ben Sinclair.

http://www.webmaster-resources101.com Ben Sinclair is the Webmaster of Webmaster Resources 101 (http://www.webmaster-resources101.com/) and Webmaster Forums 101 (http://www.webmaster-forums101.com/)

If you found this post useful you may also want to check these out:

  1. Convert Images to Thumbnails Images Using PHP
  2. Generate Random Quotes with PHP
  3. Building Easy Text or Images Scrolling with Flash MX 2004
  4. Making a JavaScript Tree Menuing System
  5. A Simple Hit Counter
  6. How To Send Email With Perl, Part I