Home >Backend Development >PHP Tutorial >How to Recursively List Files in Subdirectories with PHP?
PHP: Listing Files Recursively in Subdirectories
To list all files in a directory, including subdirectories, and store the results in an array, PHP offers several built-in functions that work together.
Using RecursiveIteratorIterator and RecursiveDirectoryIterator
The following code demonstrates how to achieve your desired result:
<code class="php">$directory = "foldername"; // Create a RecursiveDirectoryIterator object for the specified directory $directoryIterator = new RecursiveDirectoryIterator($directory); // Create a RecursiveIteratorIterator object for the directory iterator $iterator = new RecursiveIteratorIterator($directoryIterator, RecursiveIteratorIterator::SELF_FIRST); // Initialize an empty array to store the file names $files = []; // Iterate over the files in the directory foreach ($iterator as $filename) { // Filter out "." and ".." directories if ($filename->isDir()) { continue; } // Add the file name to the array $files[] = $filename; }</code>
Explanation
The RecursiveDirectoryIterator class creates an object that iterates through the files and directories in the specified path. The RecursiveIteratorIterator class provides a recursive iteration over a RecursiveIterator object, ensuring that subdirectories are also explored.
By filtering out "." and ".." directories with the isDir() method, we only add actual files to the $files array.
PHP Documentation
The above is the detailed content of How to Recursively List Files in Subdirectories with PHP?. For more information, please follow other related articles on the PHP Chinese website!