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

120

我正在尝试遍历目录中的所有文件,如果有一个目录,就会遍历它的所有文件,直到没有更多目录可供访问为止。每个处理过的项目都将添加到下面函数中的结果数组中。但它并没有起作用,我不确定我该怎么做/我做错了什么,但是当处理以下代码时,浏览器运行速度极慢,感谢您的帮助!

代码:

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

11
RecursiveDirectoryIterator - u_mulder
20个回答

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

或者:realpath("$path/$file");将路径和文件名组合起来,然后返回规范化的绝对路径。 - user2226755

1
这是对majick的回答进行的小修改。
我只是更改了函数返回的数组结构。

来自:

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

To:

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

如果有和我一样期望得到完全相同结果的人,这可能会有所帮助。


1
如果您正在使用Laravel,则可以使用Storage外观上的allFiles方法递归获取所有文件,如文档中所示: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::allFiles(storage_path('app'))
    }

}


1

对于需要先列出文件而不是文件夹的人(按字母顺序)。

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

我花了两天时间才做到这一点,不想让其他人也浪费时间,希望能帮助到某些人。

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
)

1

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

如果您使用PHP 7,则可以使用生成器并像这样优化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

{{链接1:yield from}}


1

准备好了常见使用情况的复制粘贴功能,这是上面一个答案的改进/扩展版本:

function getDirContents(string $dir, int $onlyFiles = 0, string $excludeRegex = '~/\.git/~', int $maxDepth = -1): array {
    $results = [];
    $scanAll = scandir($dir);
    sort($scanAll);
    $scanDirs = []; $scanFiles = [];
    foreach($scanAll as $fName){
        if ($fName === '.' || $fName === '..') { continue; }
        $fPath = str_replace(DIRECTORY_SEPARATOR, '/', realpath($dir . '/' . $fName));
        if (strlen($excludeRegex) > 0 && preg_match($excludeRegex, $fPath . (is_dir($fPath) ? '/' : ''))) { continue; }
        if (is_dir($fPath)) {
            $scanDirs[] = $fPath;
        } elseif ($onlyFiles >= 0) {
            $scanFiles[] = $fPath;
        }
    }

    foreach ($scanDirs as $pDir) {
        if ($onlyFiles <= 0) {
            $results[] = $pDir;
        }
        if ($maxDepth !== 0) {
            foreach (getDirContents($pDir, $onlyFiles, $excludeRegex, $maxDepth - 1) as $p) {
                $results[] = $p;
            }
        }
    }
    foreach ($scanFiles as $p) {
        $results[] = $p;
    }

    return $results;
}

如果需要相对路径:

function updateKeysWithRelPath(array $paths, string $baseDir, bool $allowBaseDirPath = false): array {
    $results = [];
    $regex = '~^' . preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', realpath($baseDir)), '~') . '(?:/|$)~s';
    $regex = preg_replace('~/~', '/(?:(?!\.\.?/)(?:(?!/).)+/\.\.(?:/|$))?(?:\.(?:/|$))*', $regex); // limited to only one "/xx/../" expr
    if (DIRECTORY_SEPARATOR === '\\') {
        $regex = preg_replace('~/~', '[/\\\\\\\\]', $regex) . 'i';
    }
    foreach ($paths as $p) {
        $rel = preg_replace($regex, '', $p, 1);
        if ($rel === $p) {
            throw new \Exception('Path relativize failed, path "' . $p . '" is not within basedir "' . $baseDir . '".');
        } elseif ($rel === '') {
            if (!$allowBaseDirPath) {
                throw new \Exception('Path relativize failed, basedir path "' . $p . '" not allowed.');
            } else {
                $results[$rel] = './';
            }
        } else {
            $results[$rel] = $p;
        }
    }
    return $results;
}

function getDirContentsWithRelKeys(string $dir, int $onlyFiles = 0, string $excludeRegex = '~/\.git/~', int $maxDepth = -1): array {
    return updateKeysWithRelPath(getDirContents($dir, $onlyFiles, $excludeRegex, $maxDepth), $dir);
}

此版本解决/改进了以下问题:

  1. 在PHP的open_basedir未覆盖..目录时,realpath会发出警告。
  2. 不使用引用来获取结果数组
  3. 允许排除目录和文件
  4. 允许仅列出文件/目录
  5. 允许限制搜索深度
  6. 总是将目录排在前面进行输出排序(因此可以按相反顺序删除/清空目录)
  7. 允许获取具有相对键的路径
  8. 针对数十万甚至数百万个文件进行了大量优化
  9. 在评论中写更多 :)

示例:

// list only `*.php` files and skip .git/ and the current file
$onlyPhpFilesExcludeRegex = '~/\.git/|(?<!/|\.php)$|^' . preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', realpath(__FILE__)), '~') . '$~is';

$phpFiles = getDirContents(__DIR__, 1, $onlyPhpFilesExcludeRegex);
print_r($phpFiles);

// with relative keys
$phpFiles = getDirContentsWithRelKeys(__DIR__, 1, $onlyPhpFilesExcludeRegex);
print_r($phpFiles);

// with "include only" regex to include only .html and .txt files with "/*_mails/en/*.(html|txt)" path
'~/\.git/|^(?!.*/(|' . '[^/]+_mails/en/[^/]+\.(?:html|txt)' . ')$)~is'

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

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


0
我找到了这段简单的代码: https://dev59.com/14Hba4cB1Zd3GeqPXuoT#24981012
 $Directory = new RecursiveDirectoryIterator($path);
 $Iterator = new RecursiveIteratorIterator($Directory);
 //Filter to get only PDF, JPEG, JPG, GIF, TIF files.
 $Regex = new RegexIterator($Iterator, '/^.+(.jpe?g|.gif|.png|.tif|.pdf)$/i', RecursiveRegexIterator::GET_MATCH);

    foreach($Regex as $val => $Regex){
       echo "$val\n<br>";
    }

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接