How to calculate folder size in php (recursively)

怪我咯
Release: 2023-03-12 18:12:01
Original
2281 people have browsed it

This article mainly introduces how PHP uses recursion to calculate the folder size. The code is very simple to use and is recommended to everyone here.

The method is very simple, I won’t go into too much nonsense here, just give you the code:

The code is as follows:

protected function dir_size($dir){
        $dh = opendir($dir);             //打开目录,返回一个目录流
        $size = 0;      //初始大小为0 
        while(false !== ($file = @readdir($dh))){     //循环读取目录下的文件
           if($file!='.' and $file!='..'){
            $path = $dir.'/'.$file;     //设置目录,用于含有子目录的情况
                if(is_dir($path)){
                $size += $this->dir_size($path);  //递归调用,计算目录大小
                }elseif(is_file($path)){
                    $size += filesize($path);   //计算文件大小
                }
            } 
        }   
        closedir($dh);             //关闭目录流
        return $size;               //返回大小
    }
Copy after login

The above is the detailed content of How to calculate folder size in php (recursively). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!