Below is a script which i use to return a random image in a specified directory. (It also sets a session variable to cache a list of images recently displayed, but that is irrelevant to my problem.) I am looking to have this script also find files in the sub-directories of $folder. At the very bottom is a function which someone showed me, but unfortunately i can not get this to work properly for me, even tho it works fine alone. If anyone can figure out how to properly integrate it, i would really appreciate it. Also, it does not have to be a function, whatever is easiest.
<?php
$folder = 'stash1/';
$exts = 'jpg jpeg png gif';
$files = array(); $i = -1; // Initialize some variables
if ('' == $folder) $folder = './';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) { // for each extension check the extension
if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
$files[0] = null;
$files[] = $file; // its good
++$i;
}
}
}
closedir($handle); // We're not using it anymore
mt_srand((double)microtime()*1000000); // seed for PHP < 4.2
// $i was incremented as we went along
session_start();
$rand = mt_rand(1, count($files)-1);
while(in_array($rand,$_SESSION['rand_img'])) {
$rand = mt_rand(1, count($files)-1);
}
// Check if the array has 50 indexes, and remove the first index if it does
if(count($_SESSION['rand_img']) >= 100) {
// $removed = array_shift($_SESSION['rand_img']);
array_shift($_SESSION['rand_img']);
}
// No need for $i, [] will insert the $rand in the next location.
$key = $rand;
$_SESSION['rand_img'][] = $key;
header('Location: '.$folder.$files[$key]);
?>
THE FUNCTION I WAS ADVISED TO USE...
function file_array($path, $exclude = ".|..", $recursive = true) {
$path = rtrim($path, "/") . "/";
$folder_handle = opendir($path);
$exclude_array = explode("|", $exclude);
$result = array();
while(false !== ($filename = readdir($folder_handle))) {
if(!in_array(strtolower($filename), $exclude_array)) {
if(is_dir($path . $filename . "/")) {
// Need to include full "path" or it's an infinite loop
if($recursive) $result[] = file_array($path . $filename . "/", $exclude, true);
} else {
$result[] = $filename;
}
}
}
return $result;
}