Hi I am trying to show all files and folders in a dir with php
e.g
Dir: system/infomation/
Folder - User
Files From User - User1.txt
Files From User - User2.txt
Files From User - User3.txt
Files From User - User4.txt
Folder - Players
Files From Players - Player1.txt
Files From Players - Player2.txt
Files From Players - Player3.txt
Files From Players - Player4.txt
Can someone lead me down the right street please
Thank You
PHP 5 has the RecursiveDirectoryIterator
.
The manual has a basic example:
<?php
$directory = '/system/infomation/';
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
while($it->valid()) {
if (!$it->isDot()) {
echo 'SubPathName: ' . $it->getSubPathName() . "\n";
echo 'SubPath: ' . $it->getSubPath() . "\n";
echo 'Key: ' . $it->key() . "\n\n";
}
$it->next();
}
?>
Edit -- Here's a slightly more advanced example (only slightly) which produces output similar to what you want (i.e. folder names then files).
// Create recursive dir iterator which skips dot folders
$dir = new RecursiveDirectoryIterator('./system/information',
FilesystemIterator::SKIP_DOTS);
// Flatten the recursive iterator, folders come before their files
$it = new RecursiveIteratorIterator($dir,
RecursiveIteratorIterator::SELF_FIRST);
// Maximum depth is 1 level deeper than the base folder
$it->setMaxDepth(1);
// Basic loop displaying different messages based on file or folder
foreach ($it as $fileinfo) {
if ($fileinfo->isDir()) {
printf("Folder - %s\n", $fileinfo->getFilename());
} elseif ($fileinfo->isFile()) {
printf("File From %s - %s\n", $it->getSubPath(), $fileinfo->getFilename());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With