Home > Backend Development > PHP Tutorial > How to List Files in a Directory and its Subdirectories in PHP?

How to List Files in a Directory and its Subdirectories in PHP?

Mary-Kate Olsen
Release: 2024-11-03 12:26:03
Original
912 people have browsed it

How to List Files in a Directory and its Subdirectories in PHP?

Listing Files in Directory and Subdirectories in PHP

In PHP, you can utilize directory iteration methods to traverse through a given directory and its subdirectories, effectively retrieving a list of all files within their hierarchical structure.

To achieve this, employ the following steps:

  1. Instantiate a RecursiveDirectoryIterator object to recursively explore the directory and its subdirectories.
  2. Create a RecursiveIteratorIterator to wrap the RecursiveDirectoryIterator and provide a way to iterate through the objects in a nested fashion.
  3. Within the loop, filter out items like "." and ".." representing the current and parent directories, respectively.
  4. To obtain the filename, use the $filename variable.

Here's an example that returns an array of file paths:

<code class="php">$files = array();
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $filename) {
    // filter out "." and ".."
    if ($filename->isDir()) continue;

    $files[] = $filename->getPathname();
}</code>
Copy after login

The resulting $files array will contain the full paths to all files in the current directory and its subdirectories. For instance, it could resemble:

<code class="php">array("folder1/file.jpg", "folder2/blah.word", "root/name.fileext")</code>
Copy after login

The above is the detailed content of How to List Files in a Directory and its 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template