Retrieving a list of all files within a directory is a common task in PHP. However, what if you need to include files from subdirectories as well? This guide explores how to accomplish this.
To list all files in a directory, including those in subdirectories, you can utilize the following code:
<code class="php">foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $filename) { // Filter out "." and ".." if ($filename->isDir()) continue; echo "$filename\n"; }</code>
This solution employs two classes from the PHP standard library: RecursiveDirectoryIterator and RecursiveIteratorIterator. Let's break down the code:
The subsequent loop iterates through all the files in the directory and subdirectories, printing their names if they are not directories.
The above is the detailed content of How do I recursively list all files in a directory in PHP?. For more information, please follow other related articles on the PHP Chinese website!