4 Ways To List Files & Folders In PHP (Simple Examples)

Welcome to a tutorial on how to list files and folders in PHP. So you need to get the contents of a folder in PHP? Well, be prepared for a small nasty surprise.

The common ways to list files and folders in PHP are:

  • foreach (scandir("FOLDER") as $ff) { ... }
  • foreach (glob("FOLDER/*") as $ff) { ... }
  • Open and read the folder.
    • $dh = opendir("FOLDER");
    • while ($ff = readdir($dh)) { ... }
  • Use an iterator.
    • $it = new DirectoryIterator("FOLDER");
    • foreach ($it as $ff) { ... }

That covers the basics, but just what is the difference? Read on for more examples!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

PHP GET FILES FOLDERS

All right, let us now get into the examples of getting files and folders in PHP.

 

TUTORIAL VIDEO

 

METHOD 1) SCANDIR

1A) BASIC SCANDIR

1a-scandir.php
<?php
// (A) GET FILES/FOLDERS
$dir = "YOUR/FOLDER/";
$all = array_diff(scandir($dir), [".", ".."]);
$eol = PHP_EOL;
 
// (B) LOOP THROUGH ALL
foreach ($all as $ff) {
  if (is_file($dir . $ff)) { echo "{$ff} - file {$eol}"; }
  if (is_dir($dir . $ff)) { echo "{$ff} - folder {$eol}"; }
}
  • scandir("FOLDER") will give you the full list of files and folders within the specified folder in an array.
  • Take note, this also includes the hidden . and ... For those who are new, these represent the current and parent folder respectively.
  • We are not interested in the “dots”, so we remove them using array_diff().
  • The rest is self-explanatory – Loop through the files and folders.

 

 

1B) SCANDIR READ SUB-FOLDERS

1b-scandir.php
<?php
// (A) RECURSIVE SCAN
function rscan ($dir) {
  $all = array_diff(scandir($dir), [".", ".."]);
  $eol = PHP_EOL;
  foreach ($all as $ff) {
    if (is_file($dir . $ff)) { echo "{$ff} - file {$eol}"; }
    if (is_dir($dir . $ff)) {
      echo "{$ff} - folder {$eol}";
      rscan("$dir$ff/");
    }
  }
}
 
// (B) GO!
rscan("YOUR/FOLDER/");

If you need to “dig” into the sub-folders, create a recursive function – If the entry is a folder, pass it back into the recursive function itself.

 

METHOD 2) GLOB

2A) BASIC GLOB

2a-glob.php
// (A) GET FILES/FOLDERS
$all = glob("YOUR/FOLDER/*");
// $all = glob("YOUR/FOLDER/*.{jpg,jpeg,webp,png,gif}", GLOB_BRACE);
$eol = PHP_EOL;
 
// (B) LOOP THROUGH ALL
foreach ($all as $ff) {
  if (is_file($ff)) { echo "{$ff} - file {$eol}"; }
  if (is_dir($ff)) { echo "{$ff} - folder {$eol}"; }
}

Now, scandir() will fetch everything. If you only need certain file types – glob() is the best option.

 

 

2B) GLOB READ SUB-FOLDERS

2b-glob.php
// (A) RECURSIVE GLOB
function rglob ($dir, $ext="*") {
  // (A1) GET FILES
  $eol = PHP_EOL;
  foreach (glob("$dir$ext", GLOB_BRACE) as $ff) {
    if (is_file($ff)) { echo "{$ff} - file {$eol}"; }
  }
 
  // (A2) GET FOLDERS
  foreach (glob("$dir*", GLOB_ONLYDIR | GLOB_MARK) as $ff) {
    echo "{$ff} - folder {$eol}";
    rglob($ff, $ext);
  }
}
 
// (B) GO!
rglob("YOUR/FOLDER/");
// rglob("YOUR/FOLDER/", "*.{jpg,jpeg,webp,png,gif}");

A “recursive glob” is slightly more roundabout, but basically – Get the files first, then recursive “dig” into the folder.

 

METHOD 3) OPENDIR

3A) BASIC OPENDIR

3a-opendir.php
<?php
// (A) OPEN DIR
$dir = "YOUR/FOLDER/";
$dh = opendir($dir) or exit("Error opening $dir");
$eol = PHP_EOL;
 
// (B) READ DIR
while ($ff = readdir($dh)) { if ($ff!="." && $ff!="..") {
  $ff = $dir . $ff;
  if (is_file($ff)) { echo "{$ff} - file {$eol}"; }
  if (is_dir($ff)) { echo "{$ff} - folder {$eol}"; }
}}

The above methods will “fetch everything into an array”. Some of you sharp code ninjas should have already caught the potential problem – What if there are thousands of files in the folder? This will run into performance and memory issues. So instead of “getting everything at once”, opendir() and readdir() will read “entry by entry”.

 

3B) OPENDIR READ SUB-FOLDERS

3a-opendir.php
<?php
// (A) RECURSIVE OPEN-READ
function rread ($dir) {
  $dh = opendir($dir);
  $eol = PHP_EOL;
  while ($ff = readdir($dh)) { if ($ff!="." && $ff!="..") {
    $ff = $dir . $ff;
    if (is_file($ff)) { echo "{$ff} - file {$eol}"; }
    if (is_dir($ff)) {
      echo "{$ff} - folder {$eol}";
      rread("$ff/");
    }
  }}
}
 
// (B) GO!
rread("YOUR/FOLDER/");

Well, this should not be a surprise by now. Create a recursive function to open and read sub-folders.

 

 

METHOD 4) DIRECTORY ITERATOR

4A) BASIC ITERATOR

4a-iterator.php
<?php
// (A) NEW DIRECTORY ITERATOR
$iterator = new DirectoryIterator("YOUR/FOLDER/");
$eol = PHP_EOL;
 
// (B) LOOP FOLDER
foreach ($iterator as $ff) {
  if ($ff->isDot()) { continue; }
  if ($ff->isFile()) { echo "{$ff->getFilename()} - file {$eol}"; }
  if ($ff->isDir()) { echo "{$ff->getFilename()} - folder {$eol}"; }
}

Lastly, here is the “alternative” way to read a folder entry by entry – Using a DirectoryIterator.

 

4B) ITERATOR READ SUB-FOLDERS

4b-iterator.php
<?php
// (A) RECURSIVE ITERATOR
function riterate ($dir) {
  $iterator = new DirectoryIterator($dir);
  $eol = PHP_EOL;
  foreach ($iterator as $ff) {
    if ($ff->isDot()) { continue; }
    if ($ff->isFile()) { echo "{$ff->getFilename()} - file {$eol}"; }
    if ($ff->isDir()) {
      echo "{$ff->getFilename()} - folder {$eol}";
      riterate("{$dir}{$ff->getFilename()}/");
    }
  }
}
 
// (B) GO!
riterate("YOUR/FOLDER/");

Well… You guys should be masters of recursive functions by now.

 

 

EXTRAS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

EXTRA) COMBINING GLOB & ITERATOR

5-glob-iterate.php
// (A) GLOB ITERATOR
$dir = "D:/DOCS/";
$eol = PHP_EOL;
// $iterator = new ArrayObject(glob("$dir*.{jpg,jpeg,gif,png,bmp,webp}", GLOB_BRACE));
$iterator = new ArrayObject(glob("$dir*", GLOB_BRACE));
$iterator = $iterator->getIterator();
 
/* (B) OPTIONAL - PAGINATION
$pgNow = 0; // current page
$pgPage = 10; // entries per page
$iterator = new LimitIterator($iterator, $pgNow * $pgPer, $pgPer);
*/
 
// (C) LOOP
foreach ($iterator as $ff) {
  if (is_file($ff)) { echo "{$ff} - file {$eol}"; }
  if (is_dir($ff)) { echo "{$ff} - folder {$eol}"; }
}

Which is the “best method”? I will say “all of them”, whichever works for you is the best. But personally, my “best solution” is a combination of glob and iterator – This is very flexible, capable of restricting by the file types, and also easily do pagination with it.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

1 thought on “4 Ways To List Files & Folders In PHP (Simple Examples)”

Comments are closed.