php递归遍历目录计算其大小(文件包括目录和普通文件)

时间:2021-10-17 20:19:23
<?php
function countdir($path){
    $size = 0; //size = 0; 跟 size = null; 怎么结果不一样
    $path = rtrim($path, '/').'/'; //因为用户输入的路径带不带/都可以,所以我这里要处理一下
    $handle = opendir($path); //打开一个句柄
    while($file = readdir($handle)){    //读取句柄中的文件,包括目录和文件
        if($file == '.' || $file == '..'){    //把这两个读取的目录给排除掉
            continue;    //跳出这两次循环,回到while继续执行
        }
        // $size = 0; 不能在这定义,每次递归到这里都是清空了,因为size是局部变量
        $realpath = $path.$file;
        if(is_dir($realpath)){
            $size += countdir($realpath);    //这里要加上以前遍历的大小
        }else if(is_file($realpath)){
            $size += filesize($realpath);
        }
    }

    return $size;
}

$path = "../../";
echo countdir($path);
?>