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'));
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; }
This code:
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!