- How to List Files in a Directory in PHP
- The opendir , readdir , and closedir Functions
- 4 Ways To List Files & Folders In PHP (Simple Examples)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- PHP GET FILES FOLDERS
- METHOD 1) SCANDIR
- 1A) BASIC SCANDIR
- 1B) SCANDIR READ SUB-FOLDERS
- METHOD 2) GLOB
- 2A) BASIC GLOB
- 2B) GLOB READ SUB-FOLDERS
- METHOD 3) OPENDIR
- 3A) BASIC OPENDIR
- 3B) OPENDIR READ SUB-FOLDERS
- METHOD 4) DIRECTORY ITERATOR
- 4A) BASIC ITERATOR
- 4B) ITERATOR READ SUB-FOLDERS
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- EXTRA) COMBINING GLOB & ITERATOR
- LINKS & REFERENCES
- TUTORIAL VIDEO
- INFOGRAPHIC CHEAT SHEET
- THE END
- PHP: List all files in a directory.
How to List Files in a Directory in PHP
Sajal Soni Last updated Aug 31, 2021
In this article, we’ll discuss how you can get a list of all the files in a directory in PHP.
In your day-to-day PHP development, you often need to deal with a file system—for example, getting a list of files in a specific directory. PHP provides a few different ways of reading the contents of a directory easily. Today, we’ll go through all these methods, along with examples to understand how each one works.
The opendir , readdir , and closedir Functions
In this section, we’ll discuss the opendir , readdir , and closedir functions to see how you can use them to get a list of files in a specific directory.
The opendir function allows you to open up a directory handle, which you can use along with other functions for different operations on the directory. You need to pass the path to the directory in the first argument of the opendir function. If the directory path is valid, a directory handle resource will be returned.
The readdir function allows you to read a directory. You need to provide a valid directory handle in the first argument of the readdir function, and you can iterate over all the entries and get a list of all files in a directory.
The closedir function allows you to close the directory handle which is opened by the opendir function. It’s a good practice to use the closedir function once you’re done with your operations on the directory handle (which was initially opened by the opendir function).
Now, let’s see it in action in the following example.
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.
- 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!
TLDR – QUICK SLIDES
TABLE OF CONTENTS
PHP GET FILES FOLDERS
All right, let us now get into the examples of getting files and folders in PHP.
METHOD 1) SCANDIR
1A) BASIC SCANDIR
- file "; > if (is_dir($dir . $ff)) < echo "- folder "; > >
- 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
- file "; > if (is_dir($dir . $ff)) < echo "- folder "; 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
// (A) GET FILES/FOLDERS $all = glob("YOUR/FOLDER/*"); // $all = glob("YOUR/FOLDER/*.", GLOB_BRACE); $eol = PHP_EOL; // (B) LOOP THROUGH ALL foreach ($all as $ff) < if (is_file($ff)) < echo "- file "; > if (is_dir($ff)) < echo "- folder "; > >
Now, scandir() will fetch everything. If you only need certain file types – glob() is the best option.
2B) GLOB READ SUB-FOLDERS
// (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 "- file "; > > // (A2) GET FOLDERS foreach (glob("$dir*", GLOB_ONLYDIR | GLOB_MARK) as $ff) < echo "- folder "; rglob($ff, $ext); > > // (B) GO! rglob("YOUR/FOLDER/"); // rglob("YOUR/FOLDER/", "*.");
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
- file "; > if (is_dir($ff)) < echo "- folder "; > >>
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
- file "; > if (is_dir($ff)) < echo "- folder "; 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
isDot()) < continue; >if ($ff->isFile()) < echo "getFilename()> - file "; > if ($ff->isDir()) < echo "getFilename()> - folder "; > >
Lastly, here is the “alternative” way to read a folder entry by entry – Using a DirectoryIterator .
4B) ITERATOR READ SUB-FOLDERS
isDot()) < continue; >if ($ff->isFile()) < echo "getFilename()> - file "; > if ($ff->isDir()) < echo "getFilename()> - folder "; riterate("getFilename()>/"); > > > // (B) GO! riterate("YOUR/FOLDER/");
Well… You guys should be masters of recursive functions by now.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the 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.
EXTRA BITS & LINKS
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
// (A) GLOB ITERATOR $dir = "D:/DOCS/"; $eol = PHP_EOL; // $iterator = new ArrayObject(glob("$dir*.", 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 "- file "; > if (is_dir($ff)) < echo "- folder "; > >
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
TUTORIAL VIDEO
INFOGRAPHIC CHEAT SHEET
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!
PHP: List all files in a directory.
In this beginner’s tutorial, I will show you how to list all files in a directory using PHP. We will do this using PHP’s glob function, which allows us to retrieve a list of file pathnames that match a certain pattern.
For this example, I have created a folder called “test”. Inside the folder, I have created three files:
Here is a screenshot of the directory:
In our first PHP code snippet, we will simply list everything that is in the test folder:
The result will look something like this:
test/file.php test/names.txt test/test.txt
However, what if we wanted to list all files with a particular file extension? i.e. What if we only want to list the .txt files and not the .php file that is currently present?
Well, the solution is pretty simple:
//Get a list of all files ending in .txt $fileList = glob('test/*.txt');
In the code snippet above, we told the glob function to return a list of file pathnames that ended .txt
Warning: In some cases, the folder may have subdirectories. In cases where you are listing everything that is inside a specified folder, these subdirectories will be returned by the glob function. To avoid printing out or interacting with subdirectories, you can simply use the is_file function to confirm that the file pathname in question leads to an actual file:
Hopefully, this tutorial was useful!