PHP package Traverse Folder all file functions

Whether at work or in interviews, you will encounter a file needs to traverse the record here, files and folders function package Traverse Folder

<?php
function my_dir($dir) {
    $files = array();
    //注意这里要加一个@,不然会有warning错误提示:)
    if(@$handle = opendir($dir)) { 
        while(($file = readdir($handle)) !== false) {
            if($file != ".." && $file != ".") { //排除根目录;
                if(is_dir($dir."/".$file)) { 
                     //如果是子文件夹,就进行递归
                    $files[$file] = my_dir($dir."/".$file);
                } else { 
                    //不是就将文件的名字存入数组;
                    $files[] = $file;
                }
            }
        }
        closedir($handle);
        print_r($files);
        return $files;
    }
}

//输出结果:
Array
(
    [0] => aaa.html
)
Array
(
    [0] => c.html
    [1] => b.html
    [abc] => 
)

Or the following function, can be flexibly altered according to the requirements

<?php

function my_dir2($dir_path) {
     if(is_dir($dir_path)) {
         $dirs = opendir($dir_path);
         if($dirs) {
             while(($file = readdir($dirs)) !== false) {
                 if($file !== '.' && $file !== '..') {
                     if(is_dir($file)) {
                          echo $dir_path . '/' . $file; echo PHP_EOL;
                         my_dir2($dir_path . '/' . $file);
                    } else {
                         echo $dir_path . '/' . $file; echo PHP_EOL;
                     }
                }
             }
             closedir($dirs);
        }
     } else {
         echo '目录不存在!';
     }
 }
 
 //输出结果:
/home/www/aaa/bbb/c.html
/home/www/aaa/bbb/b.html
/home/www/aaa/bbb/abc
Published 31 original articles · won praise 27 · views 20000 +

Guess you like

Origin blog.csdn.net/Hjingeng/article/details/103698720