Read all sub directories within a certain folder to display a random image.

Posted by Andy on Stack Overflow See other posts from Stack Overflow or by Andy
Published on 2010-06-17T20:46:41Z Indexed on 2010/06/17 23:13 UTC
Read the original article Hit count: 176

Filed under:

I have this code i have been using....but i need a conditional where it will read all the sub directories of /bg to select an image as opposed to a specific folder if they were on a subpage.

Heres my code so far which works perfectly for all subpages to display specific images:

//This would tell us its on the homepage if it helps:
$this->level() == 0

//This is the code so far
$path = '/home/sites/mydomain.co.uk/public_html/public/images/bg/'.$this->slug;


$homepagefile = URL_PUBLIC.'public/images/bg/'.$this->slug.'/main.jpg';

$bgimagearray = array();
$iterator = new DirectoryIterator($path);
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isFile() && !preg_match('\.jpg$/', $fileinfo->getFilename())) {
        $bgimagearray[] = "'" . $fileinfo->getFilename() . "'";
    }
}

$bgimage = array_rand($bgimagearray);

?>

<div id="bg">
    <div>
        <table cellspacing="0" cellpadding="0">
            <tr>
                <td><img src="<?php echo $file.trim($bgimagearray[$bgimage], "'"); ?>" alt=""/></td>
            </tr>
        </table>
    </div>
</div>

Any help would be appreciated, im sure its not rocket science but ive tried a few ways and cant get my head around it.

Thanks in advance.

© Stack Overflow or respective owner

Related posts about php