使用PHP递归函数列出目录中的所有文件和文件夹

时间:2014-07-16 14:48:34

标签: php recursion

我试图浏览目录中的所有文件,如果有目录,请浏览所有文件,依此类推,直到没有更多目录要去。每个处理过的项目都将添加到下面函数的结果数组中。虽然我不知道我能做什么/我做错了什么但它不能正常工作,但是当处理下面这段代码时,浏览器运行速度非常慢,感谢任何帮助!谢谢!

代码:

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

19 个答案:

答案 0 :(得分:107)

获取目录中的所有文件和文件夹,在...时不要调用函数。

您的代码:

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

答案 1 :(得分:80)

$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('path/to/folder'));

$files = array(); 

foreach ($rii as $file) {

    if ($file->isDir()){ 
        continue;
    }

    $files[] = $file->getPathname(); 

}



var_dump($files);

这将为您带来所有带路径的文件。

答案 2 :(得分:20)

它的缩短版本:

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

答案 3 :(得分:7)

获取所有文件带过滤器 (第二个参数)和目录中的文件夹,当您有.或{时,请不要调用函数{1}}。

您的代码:

..

输出(示例):

<?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$/'));

詹姆斯卡梅隆的主张。

答案 4 :(得分:4)

我的建议没有丑陋&#34; foreach&#34;控制结构是

array_keys($allFiles);

您可能只想提取文件路径,您可以通过以下方式执行此操作:

import Data.Int (Int32)
import Data.Bits ((.|.),(.&.),unsafeShiftL)
import Data.Word (Word32)
import Data.Binary
import qualified Data.ByteString as BS
import qualified Data.ByteString.Unsafe as BSU

int32_24be :: BS.ByteString -> Int32
int32_24be = \s ->
  let x =   unsafeShiftL (fromIntegral (BSU.unsafeIndex s 0)) 16
        .|. unsafeShiftL (fromIntegral (BSU.unsafeIndex s 1))  8
        .|.               fromIntegral (BSU.unsafeIndex s 2)
        :: Int32
      y = fromIntegral x :: Word32
  in fromIntegral (if x .&. 0x00800000 > 0 then y .|. 0xFF000000 else y .&. 0x00FFFFFF)

getFloat :: BS.ByteString -> Float
getFloat = (/ 2^^23) . fromIntegral . int32_24be

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

答案 5 :(得分:2)

这是Hors回答的修改版本,对我的情况稍微好一点,因为它删除了传递的基本目录,并且有一个递归开关,可以设置为false,这也很方便。另外为了使输出更具可读性,我将文件和子目录文件分开,因此首先添加文件然后添加子目录文件(参见结果我的意思。)

我尝试了一些其他的方法和建议,这就是我最终的结果。我有另一个非常相似的工作方法,但似乎失败的地方有一个没有文件的子目录,但该子目录有一个带有文件的子目录,它没有扫描子目录中的文件 - 所以某些答案可能需要针对该案例进行测试。)...无论如何我认为我也会在这里发布我的版本以防万一有人在寻找......

function get_filelist_as_array($dir, $recursive = true, $basedir = '', $include_dirs = false) {
    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)) {
                // optionally include directories in file list
                if ($include_dirs) {$subresults[] = str_replace($basedir, '', $path);}
                // optionally get file list for all subdirectories
                if ($recursive) {
                    $subdirresults = get_filelist_as_array($path, $recursive, $basedir, $include_dirs);
                    $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(或者传递文件路径现在也可以)并且可选$ recursive as false如果需要的话。结果:

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

享受!好的,回到程序我实际上正在使用它...

UPDATE 添加了额外的参数,用于在文件列表中包含目录(记住需要传递其他参数才能使用它。)例如。

$results = get_filelist_as_array($dir, true, '', true);

答案 6 :(得分:2)

这个解决方案为我完成了这项工作。 RecursiveIteratorIterator以递归方式列出所有目录和文件但未排序。该程序过滤列表并对其进行排序。

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

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

?>

答案 7 :(得分:1)

这将打印给定目录中所有文件的完整路径,您也可以将其他回调函数传递给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');

答案 8 :(得分:1)

以下是我提出的内容,而且代码行数不多

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

**点是无序列表的点。

希望这有帮助。

答案 9 :(得分:1)

这是对majick答案的稍作修改。
我只是更改了函数返回的数组结构。

发件人:

array() => {
    [0] => "test/test.txt"
}

收件人:

array() => {
    'test/test.txt' => "test.txt"
}

/**
 * @param string $dir
 * @param bool   $recursive
 * @param string $basedir
 *
 * @return array
 */
function getFileListAsArray(string $dir, bool $recursive = true, string $basedir = ''): array {
    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 = self::getFileListAsArray($path, $recursive, $basedir);
                    $results = array_merge($results, $subdirresults);
                }
            } else { // strip basedir and add to subarray to separate file list
                $subresults[str_replace($basedir, '', $path)] = $value;
            }
        }
    }
    // merge the subarray to give the list of files then subdirectory files
    if (count($subresults) > 0) {
        $results = array_merge($subresults, $results);
    }
    return $results;
}

可以为那些期望结果与我完全一样的人提供帮助。

答案 10 :(得分:0)

如果您使用 Laravel,您可以使用 getAllFiles 门面上的 Storage 方法递归获取所有文件,如此处的文档所示:https://laravel.com/docs/8.x/filesystem#get-all-files-within-a-directory

use Illuminate\Support\Facades\Storage;

class TestClass {

    public function test() {
        // Gets all the files in the 'storage/app' directory.
        $files = Storage::getAllFiles(storage_path('app'))
    }

}

答案 11 :(得分:0)

@ A-312的解决方案可能会导致内存问题,因为如果/xampp/htdocs/WORK包含许多文件和文件夹,它可能会创建一个巨大的数组。

如果您有PHP 7,则可以使用Generators并按以下方式优化PHP的内存:

function getDirContents($dir) {
    $files = scandir($dir);
    foreach($files as $key => $value){

        $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
        if(!is_dir($path)) {
            yield $path;

        } else if($value != "." && $value != "..") {
           yield from getDirContents($path);
           yield $path;
        }
    }
}

foreach(getDirContents('/xampp/htdocs/WORK') as $value) {
    echo $value."\n";
}

yield from

答案 12 :(得分:0)

添加相对路径选项:

Actual Value    Blob Section
1   0000803F
2   00000040
3   00004040
4   00008040
5   0000A040
6   0000C040
7   0000E040
8   00000041
9   00001041
10  00002041
11  00003041
12  00004041
13  00005041
14  00006041
15  00007041
16  00008041
17  00008841
18  00009041
19  00009841
20  0000A041
21  0000A841
22  0000B041
23  0000B841
24  0000C041
25  0000C841
26  0000D041
27  0000D841
28  0000E041
29  0000E841
30  0000F041
31  0000F841
32  00000042
33  00000442
34  00000842
35  00000C42
36  00001042
37  00001442
38  00001842
39  00001C42
40  00002042
0   00000000
0.9 6666663F
0.99    A4707D3F
0.999   77BE7F3F
0.9999  72F97F3F
0.99999 58FF7F3F
1   0000803F
1.5 0000C03F
2   00000040
2.5 00002040
3   00004040
3.5 00006040
4   00008040
4.25    00008840
4.5 00009040
4.75    00009840
4.9 CDCC9C40
5   0000A040
100 0000C842
1000    00007A44
10000   00401C46

输出:

function getDirContents($dir, $relativePath = false)
{
    $fileList = array();
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
    foreach ($iterator as $file) {
        if ($file->isDir()) continue;
        $path = $file->getPathname();
        if ($relativePath) {
            $path = str_replace($dir, '', $path);
            $path = ltrim($path, '/\\');
        }
        $fileList[] = $path;
    }
    return $fileList;
}

print_r(getDirContents('/path/to/dir'));

print_r(getDirContents('/path/to/dir', true));

答案 13 :(得分:0)

如果您希望以数组形式获取目录内容,而忽略隐藏的文件和目录,则可能会有所帮助。

function dir_tree($dir_path)
{
    $rdi = new \RecursiveDirectoryIterator($dir_path);

    $rii = new \RecursiveIteratorIterator($rdi);

    $tree = [];

    foreach ($rii as $splFileInfo) {
        $file_name = $splFileInfo->getFilename();

        // Skip hidden files and directories.
        if ($file_name[0] === '.') {
            continue;
        }

        $path = $splFileInfo->isDir() ? array($file_name => array()) : array($file_name);

        for ($depth = $rii->getDepth() - 1; $depth >= 0; $depth--) {
            $path = array($rii->getSubIterator($depth)->current()->getFilename() => $path);
        }

        $tree = array_merge_recursive($tree, $path);
    }

    return $tree;
}

结果将是类似的

dir_tree(__DIR__.'/public');

[
    'css' => [
        'style.css',
        'style.min.css',
    ],
    'js' => [
        'style.css',
        'style.min.css',
    ],
    'favicon.ico',
]

Source

答案 14 :(得分:0)

https://stackoverflow.com/a/24784144/5153116答案的更新版本:

function getDirContents($dir, $onlyFiles = false) {
    $results = [];
    $files = scandir($dir);
    foreach($files as $key => $value){
        if ($value === '.' || $value === '..') {
            continue;
        }

        $path = str_replace(DIRECTORY_SEPARATOR, '/', realpath($dir . '/' . $value));
        if (!is_dir($path)) {
            $results[] = $path;
        } else {
            if (!$onlyFiles) {
                $results[] = $path;
            }

            foreach (getDirContents($path, $onlyFiles) as $p) {
                $results[] = $p;
            }
        }
    }

    return $results;
}

此版本可解决/改进:

  1. 当PHP realpath未涵盖open_basedir时,从..发出警告。
  2. 不对结果数组使用引用
  3. 仅允许列出文件

答案 15 :(得分:0)

谁首先需要列出文件而不是文件夹(字母更早)。

可以使用以下功能。 这不是自调用功能。这样您将拥有目录列表,目录视图,文件 列表和文件夹列表也作为单独的数组。

我为此花了两天时间,也不希望有人也会为此浪费时间,希望对某人有所帮助。

function dirlist($dir){
    if(!file_exists($dir)){ return $dir.' does not exists'; }
    $list = array('path' => $dir, 'dirview' => array(), 'dirlist' => array(), 'files' => array(), 'folders' => array());

    $dirs = array($dir);
    while(null !== ($dir = array_pop($dirs))){
        if($dh = opendir($dir)){
            while(false !== ($file = readdir($dh))){
                if($file == '.' || $file == '..') continue;
                $path = $dir.DIRECTORY_SEPARATOR.$file;
                $list['dirlist_natural'][] = $path;
                if(is_dir($path)){
                    $list['dirview'][$dir]['folders'][] = $path;
                    // Bos klasorler while icerisine tekrar girmeyecektir. Klasorun oldugundan emin olalım.
                    if(!isset($list['dirview'][$path])){ $list['dirview'][$path] = array(); }
                    $dirs[] = $path;
                    //if($path == 'D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-content\upgrade'){ press($path); press($list['dirview']); die; }
                }
                else{
                    $list['dirview'][$dir]['files'][] = $path;
                }
            }
            closedir($dh);
        }
    }

    // if(!empty($dirlist['dirlist_natural']))  sort($dirlist['dirlist_natural'], SORT_LOCALE_STRING); // delete safe ama gerek kalmadı.

    if(!empty($list['dirview'])) ksort($list['dirview']);

    // Dosyaları dogru sıralama yaptırıyoruz. Deniz P. - info[at]netinial.com
    foreach($list['dirview'] as $path => $file){
        if(isset($file['files'])){
            $list['dirlist'][] = $path;
            $list['files'] = array_merge($list['files'], $file['files']);
            $list['dirlist'] = array_merge($list['dirlist'], $file['files']);
        }
        // Add empty folders to the list
        if(is_dir($path) && array_search($path, $list['dirlist']) === false){
            $list['dirlist'][] = $path;
        }
        if(isset($file['folders'])){
            $list['folders'] = array_merge($list['folders'], $file['folders']);
        }
    }

    //press(array_diff($list['dirlist_natural'], $list['dirlist'])); press($list['dirview']); die;

    return $list;
}

将输出类似这样的内容。

[D:\Xampp\htdocs\exclusiveyachtcharter.localhost] => Array
                (
                    [files] => Array
                        (
                            [0] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\.htaccess
                            [1] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\index.php
                            [2] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\license.txt
                            [3] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\php.php
                            [4] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\readme.html
                            [5] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-activate.php
                            [6] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-blog-header.php
                            [7] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-comments-post.php
                            [8] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-config-sample.php
                            [9] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-config.php
                            [10] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-cron.php
                            [11] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-links-opml.php
                            [12] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-load.php
                            [13] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-login.php
                            [14] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-mail.php
                            [15] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-settings.php
                            [16] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-signup.php
                            [17] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-trackback.php
                            [18] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\xmlrpc.php
                        )

                    [folders] => Array
                        (
                            [0] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\exclusiv_excluwlsql
                            [1] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-admin
                            [2] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-content
                            [3] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-includes
                        )

                )

dirview输出

    [dirview] => Array
        (
            [0] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\.htaccess
            [1] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\index.php
            [2] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\license.txt
            [3] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\php.php
            [4] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\readme.html
            [5] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-activate.php
            [6] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-blog-header.php
            [7] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-comments-post.php
            [8] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-config-sample.php
            [9] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-config.php
            [10] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-cron.php
            [11] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-links-opml.php
            [12] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-load.php
            [13] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-login.php
            [14] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-mail.php
            [15] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-settings.php
            [16] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-signup.php
            [17] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\wp-trackback.php
            [18] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\xmlrpc.php
            [19] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost
            [20] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\exclusiv_excluwlsql\exclusiv_excluwl.sql
            [21] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\exclusiv_excluwlsql\exclusiv_excluwl.sql.zip
            [22] => D:\Xampp\htdocs\exclusiveyachtcharter.localhost\exclusiv_excluwlsql
)

答案 16 :(得分:0)

我通过一次检查迭代改进了Hors Sujet的优秀代码,以避免在结果数组中包含文件夹:

function getDirContents($dir, &$results = array()){

    $files = scandir($dir);

    foreach($files as $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;
            }   
        }
    }
    return $results;

}

答案 17 :(得分:0)

这里有我的例子

列出使用PHP递归函数读取的目录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

答案 18 :(得分:0)

这是我的:

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