Home > Article > Backend Development > How Can I Recursively Find Files and Folders in PHP Without Performance Issues?
Finding Files and Folders Recursively with PHP
To traverse a directory's contents and all subdirectories, a recursive function is employed. However, the code provided has a performance issue, causing the browser to slow down significantly.
The Issue
The function doesn't exclude "." and ".." directories from the recursive calls, leading to an infinite loop and slow execution.
The Fix
To address this issue, we modified the code 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; }
Exclusion of "." and ".."
We added conditions to exclude "." and ".." directories from the recursive calls. These directories represent the current and parent directories, respectively, and their inclusion would create an infinite loop.
Usage
To use the function, simply provide the path to the directory you want to traverse:
var_dump(getDirContents('/xampp/htdocs/WORK'));
This code will return an array containing the complete list of files and folders within the specified directory. Each entry will be the full path to the file or folder.
The above is the detailed content of How Can I Recursively Find Files and Folders in PHP Without Performance Issues?. For more information, please follow other related articles on the PHP Chinese website!