1

I have a folder on my server called 'images', and within that folder I could have a single folder to as many as 10 folders that contain images.

Instead of writing a tag for each image

<img src="images/people/001.jpg">
<img src="images/landscape/001.jpg">

etc etc

Can I use PHP to get all the images in all the folders in the main directory 'images'?

I have VERY little experience with PHP, so this is something I am struggling with.

I need php to return an array of '<div class="box"><img src="images/FOLDER/IMAGENAME.jpg"></div>'

Maybe someone can help.

Ryan
  • 2,144
  • 8
  • 28
  • 39

2 Answers2

3
function ListFiles($dir) {
    if($dh = opendir($dir)) {
        $files = Array();
        $inner_files = Array();
        while($file = readdir($dh)) {
            if($file != "." && $file != ".." && $file[0] != '.') {
                if(is_dir($dir . "/" . $file)) {
                    $inner_files = ListFiles($dir . "/" . $file);
                    if(is_array($inner_files)) $files = array_merge($files, $inner_files); 
                } else {
                    array_push($files, $dir . "/" . $file);
                }
            }
        }
        closedir($dh);
        return $files;
    }
}
foreach (ListFiles('/path/to/images') as $key=>$file){
    echo "<div class=\"box\"><img src=\"$file\"/></div>";
}

Something like this?

Ben Ashton
  • 1,385
  • 10
  • 15
3

A simpler soluton. You can use built-in glob function. Assuming that all of your images are .jpg:

$result = array();
$dir    = 'images/';

foreach(glob($dir.'*.jpg') as $filename) {
    $result[] = "<div class=\"box\"><img src=\"$filename\"></div>";
}

Then you can echo each element of $result or whatever you want.

Muhammad Abrar
  • 2,292
  • 1
  • 15
  • 13
  • This is much simpler but because I'll no control over the image files that go into the site, it's best it can accept all image types. It's going into a web template. – Ryan Mar 09 '12 at 05:09
  • @Ryan then change the `glob()` parameter to accept all with `*.*` instead of `*.jpg`. – Jared May 24 '13 at 05:20