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

使用PHP递归功能列出目录中的所有文件和文件夹,php,recursion,Php,Recursion,我试图遍历一个目录中的所有文件,如果有目录,则遍历它的所有文件,依此类推,直到没有更多的目录可供访问。每个已处理项都将添加到下面函数中的结果数组中。虽然我不确定我能做什么/我做错了什么,但当处理下面的代码时,浏览器运行速度非常慢,非常感谢您的帮助,谢谢 代码: 这将为您带来所有具有路径的文件。获取目录中的所有文件和文件夹,当您有或时,不要调用函数。 您的代码: 这是Hors answer的一个修改版本,在我的情况下效果稍好,因为它去掉了在传递过程中传递的基本目录,并且有一个递归开关,可以设置为f

我试图遍历一个目录中的所有文件,如果有目录,则遍历它的所有文件,依此类推,直到没有更多的目录可供访问。每个已处理项都将添加到下面函数中的结果数组中。虽然我不确定我能做什么/我做错了什么,但当处理下面的代码时,浏览器运行速度非常慢,非常感谢您的帮助,谢谢

代码:
这将为您带来所有具有路径的文件。

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

您的代码:
这是Hors answer的一个修改版本,在我的情况下效果稍好,因为它去掉了在传递过程中传递的基本目录,并且有一个递归开关,可以设置为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作为false传递。结果是:

[0]=>demo-image.png
[1] =>filelist.php
[2] =>tile.png
[3] =>2015\header.png
[4] =>2015\08\background.jpg
享受吧!好的,回到我实际使用的程序中

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


$results=get_filelist_作为数组($dir,true,,,true)

这将打印给定目录中所有文件的完整路径,您还可以将其他回调函数传递给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');
函数printFunc($path){ echo$path。“
”; } 函数recursiveDir($path、$fileFunc、$dirFunc){ $openDir=openDir($path); while(($file=readdir($openDir))!==false){ $fullFilePath=realpath(“$path/$file”); 如果($file[0]!=”){ if(is_文件($fullFilePath)){ 如果(可调用($fileFunc)){ $fileFunc($fullFilePath); } }否则{ if(可调用($dirFunc)){ $dirFunc($fullFilePath); } recursiveDir($fullFilePath、$fileFunc、$dirFunc); } } } } recursiveDir($dirToScan,'printFunc','printFunc');
使用filter(第二个参数)获取目录中的所有文件和文件夹,当您有
时,不要调用函数。

您的代码: 詹姆斯·卡梅隆的主张。

这是一个简短的版本:
这个解决方案对我起了作用。递归迭代器以递归方式列出所有未排序的目录和文件。程序过滤列表并对其进行排序

我相信有一种方法可以把它写得更短;请随意改进它。 这只是一段代码片段。你可能想拉皮条来达到你的目的

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

?>

这是我的:

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
**点是未排序列表中的点


希望这能有所帮助。

这里我举了一个例子

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

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; }
我通过一次检查迭代改进了Hors Sujet的好代码,以避免在结果数组中包含文件夹:

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$allFiles = array_filter(iterator_to_array($iterator), function($file) {
    return $file->isFile();
});
函数getDirContents($dir,&$results=array()){ $files=scandir($dir); foreach($key=>$value形式的文件){ $path=realpath($dir.DIRECTORY\u SEPARATOR.$value); if(is_dir($path)==false){ $results[]=$path; } 如果($value!=“&&&$value!=”),则为else{ getDirContents($path,$results); if(is_dir($path)==false){ $results[]=$path; } } } 返回$results; } 我的建议没有丑陋的“foreach”控制结构,这是错误的

array_keys($allFiles);
您可能只想提取文件路径,可以通过以下方式进行提取:

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

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

这是对s答案的一点修改。
我刚刚更改了函数返回的数组结构

发件人:

致:



可能对像我这样拥有完全相同预期结果的人有所帮助。

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

可以使用以下功能。 这不是自调用函数。所以你会有目录列表,目录视图,文件 列表和文件夹也作为单独的数组列出

我为此花了两天时间,不希望有人也为此浪费时间,希望能帮助别人

[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] => 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
)
dirview输出

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;
}
可用于常见用例的复制和粘贴功能,改进/扩展版本: 此版本解决/改进了以下问题:
  • 当PHP
    open\u basedir
    未覆盖
    目录时,来自
    realpath
    的警告
  • 不使用结果数组的引用
  • 允许排除目录和文件
  • 仅允许列出文件/目录
  • 允许限制搜索深度
  • 它总是首先使用目录对输出进行排序(因此可以按相反顺序删除/清空目录)
  • 允许获取路径
    ..idea
    .add.php
    .add_task.php
    .helpers
     .countries.php
    .mysqli_connect.php
    .sort.php
    .test.js
    .test.php
    .view_tasks.php
    
    <?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);
    }
    
    }
    
    ?>
    
    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; }
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
    $allFiles = array_filter(iterator_to_array($iterator), function($file) {
        return $file->isFile();
    });
    
    array_keys($allFiles);
    
    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;
    }
    
    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] => 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
    )
    
    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);
    }
    
    // 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'
    
    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' => [
            'script.js',
            'script.min.js',
        ],
        'favicon.ico',
    ]
    
    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));
    
    Array
    (
        [0] => /path/to/dir/test1.html
        [1] => /path/to/dir/test.html
        [2] => /path/to/dir/index.php
    )
    
    Array
    (
        [0] => test1.html
        [1] => test.html
        [2] => index.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";
    }
    
    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'))
        }
    
    }