How can I find all the file names of a directory or folder and its sub-directories or sub-folders. I am using scandir()
, but It returns files and sub-directory names both only from root directory. If anybody have a solution then please suggest.
<?php
$dir = 'mydir/';
$files = scandir($dir);
?>
I have found a solution. I have created a script, by using this we can get or list all the files of a directory and its sub-directories. Its working fine.In there mydir assumed as the directory path
function listDirFiles($dir){
foreach(glob("$dir/*") as $ff){
is_dir($ff) ? listDirFiles($ff) : $GLOBALS['a'][] = basename($ff);
}
}
listDirFiles('mydir');
echo "<pre>", print_r($GLOBALS['a']), "</pre>";
Try this
$filelist = array();
if ($handle = opendir("."))
{
while ($entry = readdir($handle)) {
if (is_file($entry)) {
$filelist[] = $entry;
}
}
echo "<pre>";
print_r($filelist);
closedir($handle);
}
The answer here can give you more light.
What I would do (like in the answer) is run a foreach loop for each directory and then list the files in directories in that. Basically just rinse and repeat. PHP does the scandir()
function similar to the ls
command in Linux.
This is what I use in my project, this will only return file but not folder and it's recursively.
$dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("mydir/") );
$dir->setFlags(4096 | 8192);
foreach ($dir as $value) {
echo $dir->getSubPathname();
}