views:

477

answers:

1

I am looking to modify this php code to do a recursive "search for and display image" on a single, known, directory with an unknown amount of sub-directories.

Here's the code I have that scans a single directory and echoes the files out to html:

<?php 
    foreach(glob('./img/*.jpg') as $filename)
    {
        echo '<img src="'.$filename.'"><br>';
    }
?>

Given that the base directory $base_dir="./img/"; contains sub-directories having unknown amounts and tiers of their own sub-directories which all include only .jpg file types.

Basically need to build an array of all the paths of the sub-directories.

+1  A: 

Some time ago I wrote this function to traverse a directory hierarchy. It will return all file paths contained in the given folder (but not folder paths). You should easily be able to modify it to return only files whose name ends in .jpg.

function traverse_hierarchy($path)
{
    $return_array = array();
    $dir = opendir($path);
    while(($file = readdir($dir)) !== false)
    {
        if($file[0] == '.') continue;
        $fullpath = $path . '/' . $file;
        if(is_dir($fullpath))
            $return_array = array_merge($return_array, traverse_hierarchy($fullpath));
        else // your if goes here: if(substr($file, -3) == "jpg") or something like that
            $return_array[] = $fullpath;
    }
    return $return_array;
}
zneak
thats working... thanks
CheeseConQueso