Sunday, May 9, 2010

10:31 PM

To list the content of a directory you just need to use the combination of opendir() and readdir() functions.

// directory path can be either absolute or relative
$dirPath = '.';

// open the specified directory and check if it's opened successfully 
if ($handle = opendir($dirPath)) {

   // keep reading the directory entries 'til the end 
   while (false !== ($file = readdir($handle))) {

      // just skip the reference to current and parent directory 
      if ($file != "." && $file != "..") {
         if (is_dir("$dirPath/$file")) {
            // found a directory, do something with it? 
            echo "[$file]<br>";
         } else {
            // found an ordinary file 
            echo "$file<br>";
         }
      }
   }

   // ALWAYS remember to close what you opened 
   closedir($handle);
}


When you list the files surely you need to know which of these files are actually a sub-directory. Using the is_dir()function you can test if the files is really a directory or not. What you want to do later with that directory is up to you. On the code above directories are simply printed in a square brackets to differentiate them with ordinary files

0 comments: