Multiple Random Includes from Directory with Sub-Directories
<p>I have a directory containing sub directories which each contain a series of files. I'm looking for a script that will look inside the sub directories <em>and</em> randomly return a specified number of files.</p>

<p>There are a few scripts that can search a single directories (not sub folders), and other scripts that can search sub folders but only return one file.</p>

<p>To put a little context on the situation, the returned files will be included as li's in an rotating banner.</p>

<p>Thanks in advance for any help, hopefully this is possible.</p>

<p>I think I've got there, not <em>exactly</em> what I set out to achieve but works good enough, arguably better for the purpose, I'm using the following function:</p>

<pre><code>&lt;?php function RandomFile($folder='', $extensions='.*'){
   // fix path:
    $folder = trim($folder);
    $folder = ($folder == '') ? './' : $folder;

    // check folder:
    if (!is_dir($folder)){ die('invalid folder given!'); }

    // create files array
    $files = array();

    // open directory
    if ($dir = @opendir($folder)){

        // go trough all files:
        while($file = readdir($dir)){

            if (!preg_match('/^\.+$/', $file) and 
                preg_match('/\.('.$extensions.')$/', $file)){

                // feed the array:
                $files[] = $file;                
            }            
        }        
        // close directory
        closedir($dir);    
    }
    else {
        die('Could not open the folder "'.$folder.'"');
    }

    if (count($files) == 0){
        die('No files where found :-(');
    }

    // seed random function:
    mt_srand((double)microtime()*1000000);

    // get an random index:
    $rand = mt_rand(0, count($files)-1);

    // check again:
    if (!isset($files[$rand])){
        die('Array index was not found! very strange!');
    }

    // return the random file:
    return $folder . "/" . $files[$rand];

}


$random1 = RandomFile('project-banners/website-design');
while (!$random2 || $random2 == $random1) {
    $random2 = RandomFile('project-banners/logo-design');
}
while (!$random3 || $random3 == $random1 || $random3 == $random2) {
    $random3 = RandomFile('project-banners/design-for-print');
}
?&gt;
</code></pre>

<p>And echoing the results into the container (in this case the ul):</p>

<pre><code>&lt;?php include($random1) ;?&gt;
&lt;?php include($random2) ;?&gt;
&lt;?php include($random3) ;?&gt;
</code></pre>

<p>Thanks to quickshiftin for his help, however it was a little above my skill level.</p>

<p>For info the original script which I changed an be found at:</p>

<p><a href="http://randaclay.com/tips-tools/multiple-random-image-php-script/" rel="nofollow">http://randaclay.com/tips-tools/multiple-random-image-php-script/</a></p>
