PHP MySQL Tutorial
Learn PHP and MySQL

List a Directory's Contents Using PHP

Page Details

Published by:
admin
on 12-20-2008
1 person found this article useful.

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: omg Posted on 03-08-2010 7:19 PM

this is great, thanks alot!

just started using tinygrab, which uploads my screenshots (to a sub domain-folder). would be awsome if i could use http://tiny.trstd.se like a screenshot-blog ^^

should have learned php when the web was young, but i didn't.

can someone plix help me write a script that echoes "<img src=$file><br>"; in the order of creation-date and only if the file is a png?

By: fq0029 Posted on 10-04-2011 4:02 AM

bedspreads

Your site is good Actually, i have seen your post and That was very informative and very entertaining for me. Thanks for posting Really Such Things. I should recommend your site to my friends. Cheers.

By: apudiu1 Posted on 12-17-2011 3:33 AM

Brisbane's Metal Roofing Professionals

Jones Roofing is a family owned business celebrating over 16 years in the Brisbane roofing industry.

Specialising in metal roofs, our services include new roofs, re-roofing, asbestos re-roofing, roof repairs, guttering and ceiling insulation for residential and commercial buildings.

For more please visit:www.jonesroofing.com.au

By: Rudy Posted on 12-27-2012 10:30 PM

Good Thank's Bro its

Powerfull n UseFull For me :D

By: Rudy Posted on 12-27-2012 10:35 PM

Very useful, Thank You Much :D

Powered by Community Server (Non-Commercial Edition), by Telligent Systems