用PHPrecursion函数列出目录中的所有文件和文件夹

我正在尝试浏览目录中的所有文件,并且如果有目录,请检查所有文件等,直到没有更多目录可用。 每个处理的项目都将被添加到下面的函数中的结果数组中。 它不工作,虽然我不知道我能做什么/我做错了什么,但浏览器运行速度非常缓慢,当下面的代码处理,任何帮助表示感谢,谢谢!

码:

function getDirContents($dir){ $results = array(); $files = scandir($dir); foreach($files as $key => $value){ if(!is_dir($dir. DIRECTORY_SEPARATOR .$value)){ $results[] = $value; } else if(is_dir($dir. DIRECTORY_SEPARATOR .$value)) { $results[] = $value; getDirContents($dir. DIRECTORY_SEPARATOR .$value); } } } print_r(getDirContents('/xampp/htdocs/WORK')); 

获取目录中的所有文件和文件夹,如果有,请不要调用函数...

你的代码:

 <?php function getDirContents($dir, &$results = array()){ $files = scandir($dir); foreach($files as $key => $value){ $path = realpath($dir.DIRECTORY_SEPARATOR.$value); if(!is_dir($path)) { $results[] = $path; } else if($value != "." && $value != "..") { getDirContents($path, $results); $results[] = $path; } } return $results; } var_dump(getDirContents('/xampp/htdocs/WORK')); 

输出(示例):

 array (size=12) 0 => string '/xampp/htdocs/WORK/iframe.html' (length=30) 1 => string '/xampp/htdocs/WORK/index.html' (length=29) 2 => string '/xampp/htdocs/WORK/js' (length=21) 3 => string '/xampp/htdocs/WORK/js/btwn.js' (length=29) 4 => string '/xampp/htdocs/WORK/js/qunit' (length=27) 5 => string '/xampp/htdocs/WORK/js/qunit/qunit.css' (length=37) 6 => string '/xampp/htdocs/WORK/js/qunit/qunit.js' (length=36) 7 => string '/xampp/htdocs/WORK/js/unit-test.js' (length=34) 8 => string '/xampp/htdocs/WORK/xxxxx.js' (length=30) 9 => string '/xampp/htdocs/WORK/plane.png' (length=28) 10 => string '/xampp/htdocs/WORK/qunit.html' (length=29) 11 => string '/xampp/htdocs/WORK/styles.less' (length=30) 
 $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('path/to/folder')); $files = array(); foreach ($rii as $file) { if ($file->isDir()){ continue; } $files[] = $file->getPathname(); } var_dump($files); 

这将带给你所有的path文件。

这是更短的版本:

 function getDirContents($path) { $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)); $files = array(); foreach ($rii as $file) if (!$file->isDir()) $files[] = $file->getPathname(); return $files; } var_dump(getDirContents($path)); 

获取具有filter (第二个参数)和目录中的文件夹的所有文件当你有时不要调用函数...

你的代码:

 <?php function getDirContents($dir, $filter = '', &$results = array()) { $files = scandir($dir); foreach($files as $key => $value){ $path = realpath($dir.DIRECTORY_SEPARATOR.$value); if(!is_dir($path)) { if(empty($filter) || preg_match($filter, $path)) $results[] = $path; } elseif($value != "." && $value != "..") { getDirContents($path, $filter, $results); } } return $results; } // Simple Call: List all files var_dump(getDirContents('/xampp/htdocs/WORK')); // Regex Call: List php files only var_dump(getDirContents('/xampp/htdocs/WORK', '/\.php$/')); 

输出(示例):

 // Simple Call array(13) { [0]=> string(69) "/xampp/htdocs/WORK.htaccess" [1]=> string(73) "/xampp/htdocs/WORKConverter.php" [2]=> string(69) "/xampp/htdocs/WORKEvent.php" [3]=> string(70) "/xampp/htdocs/WORKdefault_filter.json" [4]=> string(68) "/xampp/htdocs/WORKdefault_filter.xml" [5]=> string(80) "/xampp/htdocs/WORKCaching/ApcCache.php" [6]=> string(84) "/xampp/htdocs/WORKCaching/CacheFactory.php" } // Regex Call array(13) { [0]=> string(69) "/xampp/htdocs/WORKEvent.php" [1]=> string(73) "/xampp/htdocs/WORKConverter.php" [2]=> string(80) "/xampp/htdocs/WORKCaching/ApcCache.php" [3]=> string(84) "/xampp/htdocs/WORKCaching/CacheFactory.php" } 

詹姆斯·卡梅隆的主张。

这个解决scheme为我做了这个工作。 RecursiveIteratorIteratorrecursion地列出所有目录和文件,但未sorting。 程序过滤列表并对其进行sorting。

我相信有一种方法可以写得更简短。 随时改善它。 这只是一个代码片段。 你可能想把它拉到你的目的。

 <?php $path = '/pth/to/your/directories/and/files'; // an unsorted array of dirs & files $files_dirs = iterator_to_array( new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path),RecursiveIteratorIterator::SELF_FIRST) ); echo '<html><body><pre>'; // create a new associative multi-dimensional array with dirs as keys and their files $dirs_files = array(); foreach($files_dirs as $dir){ if(is_dir($dir) AND preg_match('/\/\.$/',$dir)){ $d = preg_replace('/\/\.$/','',$dir); $dirs_files[$d] = array(); foreach($files_dirs as $file){ if(is_file($file) AND $d == dirname($file)){ $f = basename($file); $dirs_files[$d][] = $f; } } } } //print_r($dirs_files); // sort dirs ksort($dirs_files); foreach($dirs_files as $dir => $files){ $c = substr_count($dir,'/'); echo str_pad(' ',$c,' ', STR_PAD_LEFT)."$dir\n"; // sort files asort($files); foreach($files as $file){ echo str_pad(' ',$c,' ', STR_PAD_LEFT)."|_$file\n"; } } echo '</pre></body></html>'; ?> 

我的提议没有丑陋的“foreach”控制结构

 $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)); $allFiles = array_filter(iterator_to_array($iterator), function($file) { return $file->isFile(); }); 

你可能只想提取文件path,你可以这样做:

 array_keys($allFiles); 

仍然是4行代码,但比使用循环或更直接的东西。

这里是Hors的一个修改版本,对于我的情况来说略微好一点,因为它剥离了传递的基本目录,并且有一个可以设置为false的recursion开关,这也很方便。 另外为了使输出更具可读性,我将文件和子目录文件分开,所以首先添加文件然后添加子目录文件(请参阅我的意思是结果)。

我尝试了其他一些方法和build议,这就是我最终的结果。 我有另一个工作方法已经非常相似,但似乎失败的地方有一个没有文件的子目录,但该子目录有一个文件的子目录,它没有扫描子目录的文件 – 所以一些答案可能需要testing)…反正以为我会在这里发布我的版本,以防万一有人在寻找…

 function get_filelist_as_array($dir, $recursive = true, $basedir = '') { if ($dir == '') {return array();} else {$results = array(); $subresults = array();} if (!is_dir($dir)) {$dir = dirname($dir);} // so a files path can be sent if ($basedir == '') {$basedir = realpath($dir).DIRECTORY_SEPARATOR;} $files = scandir($dir); foreach ($files as $key => $value){ if ( ($value != '.') && ($value != '..') ) { $path = realpath($dir.DIRECTORY_SEPARATOR.$value); if (is_dir($path)) { // do not combine with the next line or.. if ($recursive) { // ..non-recursive list will include subdirs $subdirresults = get_filelist_as_array($path,$recursive,$basedir); $results = array_merge($results,$subdirresults); } } else { // strip basedir and add to subarray to separate file list $subresults[] = str_replace($basedir,'',$path); } } } // merge the subarray to give the list of files then subdirectory files if (count($subresults) > 0) {$results = array_merge($subresults,$results);} return $results; } 

我想有一件事要注意,不要在调用它的时候向这个函数传递一个$ basedir的值…主要是传递$ dir(或者传递一个文件path现在也能工作),并且可能$ recursive为false需要。 结果:

 [0] => demo-image.png [1] => filelist.php [2] => tile.png [3] => 2015\header.png [4] => 2015\08\background.jpg 

请享用! 好的,回到程序中我正在使用这个…

这将打印给定目录中所有文件的完整path,还可以将其他callback函数传递给recursiveDir。

 function printFunc($path){ echo $path."<br>"; } function recursiveDir($path, $fileFunc, $dirFunc){ $openDir = opendir($path); while (($file = readdir($openDir)) !== false) { $fullFilePath = realpath("$path/$file"); if ($file[0] != ".") { if (is_file($fullFilePath)){ if (is_callable($fileFunc)){ $fileFunc($fullFilePath); } } else { if (is_callable($dirFunc)){ $dirFunc($fullFilePath); } recursiveDir($fullFilePath, $fileFunc, $dirFunc); } } } } recursiveDir($dirToScan, 'printFunc', 'printFunc'); 

这是我的:

 function recScan( $mainDir, $allData = array() ) { // hide files $hidefiles = array( ".", "..", ".htaccess", ".htpasswd", "index.php", "php.ini", "error_log" ) ; //start reading directory $dirContent = scandir( $mainDir ) ; foreach ( $dirContent as $key => $content ) { $path = $mainDir . '/' . $content ; // if is readable / file if ( ! in_array( $content, $hidefiles ) ) { if ( is_file( $path ) && is_readable( $path ) ) { $allData[] = $path ; } // if is readable / directory // Beware ! recursive scan eats ressources ! else if ( is_dir( $path ) && is_readable( $path ) ) { /*recursive*/ $allData = recScan( $path, $allData ) ; } } } return $allData ; } 

这是我想出来的,这是没有太多的代码行

 function show_files($start) { $contents = scandir($start); array_splice($contents, 0,2); echo "<ul>"; foreach ( $contents as $item ) { if ( is_dir("$start/$item") && (substr($item, 0,1) != '.') ) { echo "<li>$item</li>"; show_files("$start/$item"); } else { echo "<li>$item</li>"; } } echo "</ul>"; } show_files('./'); 

它输出类似的东西

 ..idea .add.php .add_task.php .helpers .countries.php .mysqli_connect.php .sort.php .test.js .test.php .view_tasks.php 

**点是无名单的点。

希望这可以帮助。

在这里我有这样的例子

列出使用PHPrecursion函数读取的目录csv(文件)中的所有文件和文件夹

 <?php /** List all the files and folders in a Directory csv(file) read with PHP recursive function */ function getDirContents($dir, &$results = array()){ $files = scandir($dir); foreach($files as $key => $value){ $path = realpath($dir.DIRECTORY_SEPARATOR.$value); if(!is_dir($path)) { $results[] = $path; } else if($value != "." && $value != "..") { getDirContents($path, $results); //$results[] = $path; } } return $results; } $files = getDirContents('/xampp/htdocs/medifree/lab');//here folder name where your folders and it's csvfile; foreach($files as $file){ $csv_file =$file; $foldername = explode(DIRECTORY_SEPARATOR,$file); //using this get your folder name (explode your path); print_r($foldername); if (($handle = fopen($csv_file, "r")) !== FALSE) { fgetcsv($handle); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $num = count($data); for ($c=0; $c < $num; $c++) { $col[$c] = $data[$c]; } } fclose($handle); } } ?> 

http://myphpinformation.blogspot.in/2016/05/list-all-files-and-folders-in-directory-csv-file-read-with-php-recursive.html

我用一个检查迭代改进了Hors Sujet的良好代码,以避免在结果数组中包含文件夹:

函数getDirContents($ dir,&$结果=数组()){

     $ files = scandir($ dir);

     foreach($文件为$ key => $ value){
         $ path = realpath($ dir.DIRECTORY_SEPARATOR。$ value);
         if(is_dir($ path)== false){
             $ results [] = $ path;
         }
         else if($ value!=“。”&& $ value!=“..”){
             getDirContents($ path,$ results);
             if(is_dir($ path)== false){
                 $ results [] = $ path;
             }   
         }
     }
    返回$结果;

 }