如何在php中列出目录及其子目录的所有文件? [关闭]

如何在php中列出目录及其子目录的所有文件?  [关闭]

问题描述:

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);
?> 

如何查找目录或文件夹及其子目录或子文件夹的所有文件名。 我正在使用 scandir() code>,但它仅从根目录返回文件和子目录名。 如果有人有解决方案,请建议。 p>

  &lt;?php 
 $ dir ='mydir /'; 
 $ files = scandir($ dir); 
?&gt;  
  code>  pre> 
  div>

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();
}