Last updated: August 25, 2026.
PHP provides iterator classes for listing folders and walking directory trees. Always construct paths from a trusted base directory and treat filenames as data rather than executable input.
List one directory
<?php
$directory = new FilesystemIterator(
__DIR__ . '/documents',
FilesystemIterator::SKIP_DOTS
);
foreach ($directory as $item) {
echo $item->getFilename();
echo $item->isDir() ? " [directory]
" : " [file]
";
}Walk all nested directories
<?php
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
__DIR__ . '/documents',
FilesystemIterator::SKIP_DOTS
),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $file) {
if ($file->isFile()) {
printf("%s (%d bytes)
", $file->getPathname(), $file->getSize());
}
}Safe path checklist
- Resolve the trusted base with
realpath(). - Reject a requested path if its resolved value is outside that base.
- Do not concatenate unchecked query-string values into filesystem paths.
- Check permissions and handle unreadable entries.
- Use
mkdir($path, 0750, true)for nested application directories. - Avoid following symbolic links unless the application explicitly supports them.
The DirectoryIterator reference lists available file metadata methods.