Home  >  Article  >  Backend Development  >  How do I recursively list all files in a directory in PHP?

How do I recursively list all files in a directory in PHP?

DDD
DDDOriginal
2024-11-03 22:06:31246browse

How do I recursively list all files in a directory in PHP?

Recursive File Listing in PHP

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.

Solution

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>

Explanation

This solution employs two classes from the PHP standard library: RecursiveDirectoryIterator and RecursiveIteratorIterator. Let's break down the code:

  • RecursiveDirectoryIterator('foldername'): Initializes a directory iterator for the folder specified in 'foldername.'
  • new RecursiveIteratorIterator($directoryIterator): Creates an iterator that recursively iterates through all directories and files within the specified directory.

The subsequent loop iterates through all the files in the directory and subdirectories, printing their names if they are not directories.

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 do I recursively list all files in a directory in 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