List all files of a directory in php

Posted by pavan - 1 year ago

List all files of a directory in php

CODE:

 function list_directory_contents($dir){

     $dh = new DirectoryIterator($dir);    
     foreach ($dh as $item) {
         if (!$item->isDot()) {
            if ($item->isDir()) {
                list_directory_contents("$dir/$item");
            } else {
                echo $dir . "/" . $item->getFilename();
                echo "<br>";
            }
         }
      }
   }

  # Call function 

  list_directory_contents("abc");

Results:

 abc/abc1.txt
   abc/abc2.txt
   abc/abc3.txt
   abc/xyz/xyz1.txt
   abc/xyz/xyz2.txt