澳洲大头 发表于 2009-12-18 14:55:17

php 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!
页: [1]
查看完整版本: php random images from a folder