PHP MySQL Tutorial
Learn PHP and MySQL

List a Directory's Contents Using PHP

100% of people found this useful
List a Directory's Contents Using PHP

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

Recent Comments

By: umangbhat3 Posted on 10-12-2015 9:15 AM

I agree with what you are saying.

Great post.

BTW check this out,

Happy Halloween 2015

Happy Halloween 2015 Wishes

Happy Halloween Wishes

Happy Halloween quotes

Happy Halloween images

www.happyrakshabandhan2015wishes.com

By: john9 Posted on 11-17-2015 6:05 AM
Powered by Community Server (Non-Commercial Edition), by Telligent Systems