Home > Backend Development > PHP Tutorial > How Can I Recursively List All Files and Folders in a Directory Using PHP?

How Can I Recursively List All Files and Folders in a Directory Using PHP?

Barbara Streisand
Release: 2024-12-02 12:37:17
Original
836 people have browsed it

How Can I Recursively List All Files and Folders in a Directory Using PHP?

Directories and Files Recursive Traversal with PHP

Q: How can I recursively list all files and folders in a directory using a PHP function?

A: To traverse a directory and its subdirectories, follow these steps:

  1. Define a PHP Function:

    function getDirContents($dir, &$results = array()) {
        $files = scandir($dir);
    
        foreach ($files as $key => $value) {
            $path = realpath($dir . DIRECTORY_SEPARATOR . $value);
    
            if (!is_dir($path)) {
                $results[] = $path;
            } else if ($value != "." && $value != "..") {
                getDirContents($path, $results);
                $results[] = $path;
            }
        }
    
        return $results;
    }
    Copy after login
  2. Retrieve Files and Folders:

    var_dump(getDirContents('/xampp/htdocs/WORK'));
    Copy after login
  3. Output:

    The output will contain a list of all files and folders in the specified directory, including subdirectories.

Improvements over the original code:

  • Avoid Infinite Recursion: The updated code ensures that the recursion is only performed on non-root directories, preventing infinite loops.
  • Use Realpath: realpath() is used to obtain the real path of the item, which resolves any symbolic links.
  • Pass Results by Reference: The results array is passed by reference to avoid copying the array at each iteration, which can improve performance.

The above is the detailed content of How Can I Recursively List All Files and Folders in a Directory Using 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