PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
you can use [php_man]glob[/php_man] or [php_man]readdir[/php_man] to get a list of the files in your directory. Then just use [php_man]rand[/php_man] or [php_man]mt_rand[/php_man] to choose the image from the list.
<?php
// chanage the directory path
$dir = '/home/mcovey/kafene.org/img';
// set valid extensions
$extentions = array('jpg', 'gif', 'png', 'jpeg', 'BMP', 'bmp', 'PNG', 'JPG', 'JPEG', 'GIF');
$images = array();
$dh = opendir($dir);
while(($file = readdir($dh)) !== false) {
// check if it's a file, and it has a valid extension
if (is_file($dir . $file) && in_array(substr($file, -3), $extentions)) {
// add image to array
$images[] = $file;
}
}
closedir($dh);
// get 1 random key
$selected = array_rand($images, 1);
// set headers
echo ($images[$selected]);
?>
I'm getting the error:
Warning: array_rand(): Second argument has to be between 1 and the number of elements in the array in /home/.halleck/mcovey/kafene.org/randimg.php on line 28