You can use the RecursiveIteratorIterator class in PHP to recursively list files in a directory and its subdirectories. Here's an example:
function listFiles($directory) {
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD
);
foreach ($iterator as $file) {
if ($file->isDir()) {
echo 'Directory: ' . $file->getPathname() . PHP_EOL;
} else {
echo 'File: ' . $file->getPathname() . PHP_EOL;
}
}
}
You can use the listFiles
function by passing the directory path as an argument:
$directory = '/path/to/directory';
listFiles($directory);
The above code will recursively list all the files and directories in the given directory, including subdirectories. The isDir
method is used to check if the current item is a directory or a file.