This script will read all images from a folder and read the files into an array. It uses rand() to get a random number. It will display a random image from the image folder given.
This script will read all images from a folder and read the files into an array.
It uses rand() to get a random number. It will display a random image from the image folder given.
The check for whether it is an image or not is made by checking the file's extension.
Programmed by Christian Haensel on Tuesday, Dec. 12, 2007.
Visit my website at http://www.chftp.com. Email me at haensel@chftp.com
This script may be redistributed, altered and whatnot. Please, if you like it and/or find it useful, link back to me.
Chris
*/
// Point to the folder containing the images. Relative path without trailing slash!
$imgfolder = "images/mini";
// Checks if the file is an image. If not, it won't be added to the image list
function is_image($filename){
$filename = strtolower($filename) ;
$ext = split("[/\\.]", $filename) ;
$n = count($ext)-1;
$ext = $ext[$n];
// Here you can list the extensions you want to be allowed
if($ext == "jpg" || $ext == "JPG" || $ext == "jpeg" || $ext == "JPEG" || $ext == "gif" || $ext == "GIF" || $ext == "png" || $ext == "PNG") {
return true;
} else {
return false;
}
}
// Read the image folder into an array
$dir = opendir($imgfolder);
$array = array();
// Run through the folder
while($file = readdir($dir)) {
// Checks if the file is an image. Check the is_image() function a but up in this file
if(is_image($file)) {
// It's an image!! Put it into the array
array_push($array, $file);
}
}
// Count the amount of images in the array
$count = (count($array)-1);
// Generate a random number
$rand = rand(0,$count);
// Select an image from the array based on the random number
$img = $array[$rand];
// Output the image
echo '<img src="'.$imgfolder.'/'.$img.'" border="1">';
?>