Home > Backend Development > PHP Tutorial > How Can I Recursively List Files from All Subdirectories in PHP?

How Can I Recursively List Files from All Subdirectories in PHP?

DDD
Release: 2024-11-03 14:27:30
Original
229 people have browsed it

How Can I Recursively List Files from All Subdirectories in PHP?

List Files Recursively from All Subdirectories in PHP

In PHP, the list all files in a directory functionality can be extended to retrieve files from subdirectories recursively. This can be valuable for organizing and accessing files within complex directory structures.

Solution:

To recursively list files from all subdirectories, you can use the following code:

<code class="php">foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $filename) {
    if ($filename->isDir()) {
        continue;
    }

    echo "$filename\n";
}</code>
Copy after login

Explanation:

  • RecursiveDirectoryIterator: Creates a new recursive directory iterator that iterates over files and directories in a given directory.
  • RecursiveIteratorIterator: Wraps the above iterator and provides additional filtering and processing capabilities.

Result:

The code creates an array-like structure ($files) containing all files from the current and all subdirectories. The output will be a list of files and their paths:

file.jpg
blah.word
name.fileext
Copy after login

Additional Resources:

  • [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 Can I Recursively List Files from All Subdirectories 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