简体   繁体   中英

Pull all images from multiple directories and display them with PHP

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.

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM