Random Image Generator (Rated 0)Description:
This function will select a random image from a given directory. It allows you to limit what type of images that can be selected. The function will search the directory for all images that are allowed. Then return a random one with the full path. Code starts here
<?php
function random_image($dir = './') {
/* array of accepted image types */
$allowed_types = array('gif','jpg','jpeg');
/* directory handle */
if(!$dh = @opendir($dir)) {
die('Unable to open directory.');
}
else {
while(($file = readdir($dh)) !== false) {
/* skip . and .. in filesystem */
if($file == '.' || $file == '..') {
continue;
}
/* verify extension */
list($name,$ext) = explode('.',$file);
if(!in_array(strtolower($ext),$allowed_types)) {
continue;
}
else {
/* store file as image */
$images[] = $file;
}
}
/* seed randamizor */
srand((float)microtime()*10000000);
/* get a random image */
$key = array_rand($images);
return $dir . '/' . $images[$key];
}
}
/* EXAMPLE USAGE
// get a random image from the images folder located in the same directory as this script
// make sure the path given does not include a backslash at the end
$image = random_image('./images');
// display the random image
echo '<img src="$image" />';
*/
?>
Submitted by php_brian on 21-03-2003 8:37 |