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:
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; }
Retrieve Files and Folders:
var_dump(getDirContents('/xampp/htdocs/WORK'));
Output:
The output will contain a list of all files and folders in the specified directory, including subdirectories.
Improvements over the original code:
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!