isuru
isuru

Reputation: 3565

How to get image names from all sub directories?

I have used following php code to get all images names from relevant directory.

$dir = "images";
$images = scandir($dir);
$listImages=array();
foreach($images as $image){
    $listImages=$image;
    echo ($listImages) ."<br>";
}

This one works perfectly. But I want to get all images file names within all sub directories from relevant directory. Parent directory does not contain images and all the images contain in sub folders as folows.

How I go through the all sub folders and get the images names?

Upvotes: 2

Views: 779

Answers (2)

Dis_Pro
Dis_Pro

Reputation: 593

Try following. To get full directory path, merge with parent directory.

$path = 'images'; // '.' for current
   foreach (new DirectoryIterator($path) as $file) {
   if ($file->isDot()) continue;

   if ($file->isDir()) {
       $dir = $path.'/'. $file->getFilename();

   $images = scandir($dir);
       $listImages=array();
       foreach($images as $image){
           $listImages=$image;
           echo ($listImages) ."<br>";
       }
   }
}

Upvotes: 1

Nick Tucci
Nick Tucci

Reputation: 356

Utilizing recursion, you can make this quite easily. This function will indefinitely go through your directories until each directory is done searching. THIS WAS NOT TESTED.

$images = [];

function getImages(&$images, $directory) {
    $files = scandir($directory); // you should get rid of . and .. too

    foreach($files as $file) {
        if(is_dir($file) {
            getImages($images, $directory . '/' . $file);
        } else {
            array_push($images, $file); /// you may also check if it is indeed an image
        }
    }
}

getImages($images, 'images');

Upvotes: 1

Related Questions