Jan 15, 2014

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

Altaf Hussain

Altaf Hussain

Altaf Hussain is a Sr. Software Developer at Techlites Solutions. He is expertise in PHP and MySQL. His interests span all aspects of programming and development including JavaScript, AJAX, JQuery, PHP, MySQL, XML, JSON and much more.

0 comments:

Post a Comment

 

Copyright @ 2013 Altaf hussain's blog.