This script outputs random image from a defined directory.
Make sure to change the path to your images directory and also an image to display if directory listing fails. I have found this piece of code handy to use to create random headers, logos when designing web pages.
Code:
<?php
$path_to_images = “/images/“; // path to your images
$default_img = “image.gif“; // image to display if directory listing fails
function getRandomImage($thispath, $img) {
if ( $list = getImagesList($thispath) ) {
mt_srand( (double)microtime() * 1000000 );
$num = array_rand($list);
$img = $list[$num];
}
return $thispath . $img;
}
function getImagesList($thispath) {
$ctr = 0;
if ( $img_dir = @opendir($thispath) ) {
while ( false !== ($img_file = readdir($img_dir)) ) {
// can add checks for other image file types here
if ( preg_match(“/(\.gif|\.jpg)$/”, $img_file) ) {
$images[$ctr] = $img_file;
$ctr++;
}
}
closedir($img_dir);
return $images;
}
return false;
}
?>
<img src=”<?php echo getRandomImage($path_to_images, $default_img) ?>;”>

























