2

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.

  • Parent Dir
    • Sub Dir
      • image1
      • image2
    • Sub Dir2
      • image3
      • image4

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

isuru
  • 3,385
  • 4
  • 27
  • 62
  • u have to use a function that calls itself. just check if Directory is empty. if not take subdirectory and use function within. this way it Loops through all Directorys – KikiTheOne Oct 12 '16 at 08:54
  • 1
    Possible duplicate of [building a simple directory browser using php RecursiveDirectoryIterator](http://stackoverflow.com/questions/6223365/building-a-simple-directory-browser-using-php-recursivedirectoryiterator) – KikiTheOne Oct 12 '16 at 08:56

2 Answers2

1

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');
Nick Tucci
  • 336
  • 4
  • 16
1

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>";
       }
   }
}
Dis_Pro
  • 633
  • 1
  • 10
  • 21