天天看点

PHP递归遍历目录

PHP实现递归遍历目录

<?php
/**
 * 递归遍历目录
 * @param string $path 目录所在路径
 * @param int $deep 递归调用的深度 默认为0
 * @return string 输出当前目录及子目录的所有文件
 */
function recursivereaddirs($path,$deep = )
{
    $dirHandle = opendir($path);
    while( false !== ($file = readdir($dirHandle)) ){
        if( $file != '.' && $file != '..'  ){
            //让文件输出更有层次感
            echo str_repeat('-', $deep*) . $file . '<br/>';
            //判断当前文件是否为目录
            if( is_dir($path . '/' . $file) ){
                //递归点 递归调用遍历目录
                recursivereaddirs($path . '/' . $file, $deep + );
            }
        }
    }
    closedir($dirHandle);
}
//调用递归遍历
recursivereaddirs('./');
?>
           

效果如图所示:

PHP递归遍历目录