2

I would like to list all .jpg files from folders and subfolders.

I have that simple code:

<?php

// directory
$directory = "img/*/";

// file type
$images = glob("" . $directory . "*.jpg");

foreach ($images as $image) {
    echo $image."<br>";
    } 

?>

But that lists .jpg files from img folder and one down.

How to scan all subfolders?

user3783243
  • 5,368
  • 5
  • 22
  • 41
Budrys
  • 98
  • 1
  • 1
  • 10

2 Answers2

0

As a directotry can contain subdirectories, and in their turn contains subdirectories, so we should use a recursive function. glob() is here not sufficient. This might work for you:

<?php
function getDir4JpgR($directory) {
  if ($handle = opendir($directory)) {
    while (false !== ($entry = readdir($handle))) {
      if($entry != "." && $entry != "..") {

        $str1 = "$directory/$entry";

        if(preg_match("/\.jpg$/i", $entry)) {
          echo $str1 . "<br />\n";          
        } else {
          if(is_dir($str1)) {
             getDir4JpgR($str1);
          }
        }       
      }
    }
    closedir($handle);
  }
}

//
// call the recursive function in the main block:
//
// directory
$directory = "img";

getDir4JpgR($directory);
?>

I put this into a file named listjpgr.php. And in my Chrome Browser, it gives this capture:

enter image description here

jacouh
  • 8,473
  • 5
  • 32
  • 43
0

Php coming with the DirectoryIterator which can be very useful in that case. Please note that this simple function can be easly improved by adding the whole path to a file instead the only file name, and maybe use something else instead of the reference.

  /*
   *  Find all file of the given type.
   *  @dir : A directory from which to start the search
   *  @ext : The extension. XXX : Dont call it with "." separator
   *  @store : A REFERENCE to an array on which store the element found.
   * */
  function allFileOfType($dir, $ext, &$store) {
    foreach(new DirectoryIterator($dir) as $subItem) {
      if ($subItem->isFile() && $subItem->getExtension() == $ext)
        array_push($store, $subItem->getFileName());
      elseif(!$subItem->isDot() && $subItem->isDir())
        allFileOfType($subItem->getPathName(), $ext, $store);
    }
  }

  $jpgStore = array();
  allFileOfType(__DIR__, "jpg", $jpgStore);
  print_r($jpgStore);