Walk a Directory Recursively with a PHP Function
If you need to traverse a directory and its subdirectories, seeking out every file and folder contained within, you can create a recursive PHP function to handle the task. Here's how:
Recursive Function Implementation
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; }
Usage
Call the function like this:
$results = getDirContents('/xampp/htdocs/WORK'); var_dump($results);
Example Output
The function will return an array containing the paths to all files and folders in the specified directory, including subdirectories. For instance, given the directory /xampp/htdocs/WORK, the output might look like this:
array (size=12) 0 => string '/xampp/htdocs/WORK/iframe.html' (length=30) 1 => string '/xampp/htdocs/WORK/index.html' (length=29) 2 => string '/xampp/htdocs/WORK/js' (length=21) 3 => string '/xampp/htdocs/WORK/js/btwn.js' (length=29) 4 => string '/xampp/htdocs/WORK/js/qunit' (length=27) 5 => string '/xampp/htdocs/WORK/js/qunit/qunit.css' (length=37) 6 => string '/xampp/htdocs/WORK/js/qunit/qunit.js' (length=36) 7 => string '/xampp/htdocs/WORK/js/unit-test.js' (length=34) 8 => string '/xampp/htdocs/WORK/xxxxx.js' (length=30) 9 => string '/xampp/htdocs/WORK/plane.png' (length=28) 10 => string '/xampp/htdocs/WORK/qunit.html' (length=29) 11 => string '/xampp/htdocs/WORK/styles.less' (length=30)
The above is the detailed content of How Can I Recursively Walk a Directory and Get All File and Folder Paths Using PHP?. For more information, please follow other related articles on the PHP Chinese website!