List all files of a directory in php

Listing all files of a directory in php is quite easy with php DirectoryIterator class. This class provides a simple interface for viewing the contents of filesystem directories.

Here is a simple php function to list all files of a directory. This is a recursive function so that it will list files of all of its subdirectories too.

   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");
  
The output will be something like

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

List all files of a directory in php List all files of a directory in php Reviewed by JS Pixels on January 15, 2014 Rating: 5

No comments:

Altaf Web. Powered by Blogger.