Home > Backend Development > PHP Tutorial > How Can I Recursively List All Files and Folders in a Directory Using PHP, Avoiding Infinite Loops and Duplicate Entries?

How Can I Recursively List All Files and Folders in a Directory Using PHP, Avoiding Infinite Loops and Duplicate Entries?

Linda Hamilton
Release: 2024-12-02 10:05:15
Original
900 people have browsed it

How Can I Recursively List All Files and Folders in a Directory Using PHP, Avoiding Infinite Loops and Duplicate Entries?

Determining Files and Folders in a Directory Utilizing Recursive PHP Functions

This discussion investigates a method for traversing a directory's files and subdirectories recursively.

The provided code:

function getDirContents($dir){
    $results = array();
    $files = scandir($dir);
    foreach($files as $key => $value){
        if(!is_dir($dir. DIRECTORY_SEPARATOR .$value)){
            $results[] = $value;
        } else if(is_dir($dir. DIRECTORY_SEPARATOR .$value)) {
            $results[] = $value;
            getDirContents($dir. DIRECTORY_SEPARATOR .$value);
        }
    }
}
print_r(getDirContents('/xampp/htdocs/WORK'));
Copy after login

The Dilemma:
The given code possesses a recursive function for exploring directories and files. However, it fails to disregard '.' and '..', resulting in a potentially endless loop. Moreover, each file and directory is duplicated in the results.

The Answer:
To address this issue, we can modify the function as follows:

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

This code:

  • Calls the realpath() function to retrieve the actual path of each file and directory, eliminating any potential traversal issues.
  • Ignores directories denoted by '.' or '..', which could lead to infinite loops.
  • Avoids duplicate entries in the results by storing them in a passed-by-reference array (&$results).

The above is the detailed content of How Can I Recursively List All Files and Folders in a Directory Using PHP, Avoiding Infinite Loops and Duplicate Entries?. 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