Home > Backend Development > PHP Tutorial > 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
Release: 2024-11-03 22:06:31
Original
338 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template