Home >Backend Development >PHP Tutorial >How to Recursively List Files in Subdirectories with PHP?

How to Recursively List Files in Subdirectories with PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 17:59:29966browse

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

  • [RecursiveDirectoryIterator](https://www.php.net/manual/en/class.recursivedirectoryiterator.php)
  • [RecursiveIteratorIterator](https://www.php.net/manual/en/class.recursiveiteratoriterator.php)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn