Just came to the company in the morning, the head told me, grasp to write a small function, used to count the file size in the specified directory, I went, do it, fortunately a little foundation, a will be completed, haha. The code is below.
<? /** Statistics Directory file size function @author xfcode * /function dirsize ($dir) {@ $dh = Opendir ($dir); $size = 0; while ($file = @readdir ($DH)) { if ($file! = "." and $file! = "...") { $path = $dir. " /". $file; if (Is_dir ($path)) {$size + = Dirsize ($path); } elseif (Is_file ($path)) { $size + = FileSize ($path); }}} @closedir ($DH); return $size; }//function End //eg: $dir _path = "./my_fil Es "; $dir _size = dirsize ($dir _path); $dir _size = $dir _size/1024/1024; Echo $dir _size. " MB ";
This function recursively iterates through all the files in the directory and calculates the total file size in megabytes.
Let's take a look at the code here.
<?php #循环遍历目录中所有的文件, and the size of the directory and file $dirName = "PhpMyAdmin"; $dir =opendir ($dirName); #返回一个资源类型 while ($fileName =readdir ($dir)) {$file = $dirName. " /". $fileName; if ($fileName! = "." && $fileName! = "...") {if (Is_dir ($file)) {echo "". $fileName. " = = = ". Date (" Y-m-d h:i:s ", Filectime ($file))." = = ". FileType ($file)." = = ". Tosize (Dirsize ($file))."
"; } else{echo "". $fileName. " ===== ". Date (" Y-m-d h:i:s ", Filectime ($file))." = = = ". FileType ($file)." = = = ". Tosize (FileSize ($file))."
"; }}} closedir ($dir); #把文件或目录的大小转化为容易读的方式 function Tosize ($size) {$dw; #指定文件或目录统计的单位方式 if ($size >pow (2,30)) {$DW = "GB"; $size =round ($size/pow (2,30), 2); } else if ($size >pow (2,20)) {$DW = "MB"; $size =round ($size/pow (2,20), 2); } else if ($size >pow (2,10)) {$DW = "KB"; $size =round ($size/pow (2,10), 2); } else {$dw = "bytes";} return $size. $dw; } #利用递归的方式统计目录的大小 function Dirsize ($dirName) {$dirsize =0; $dir =opendir ($dirName); while ($fileName =readdir ($dir)) {$ file= $dirName. " /". $fileName; if ($fileName! = "." && $fileName! = "...") {//must be judged, otherwise an error will occur if (Is_dir ($file)) {$dirsize +=dirsize ($file); } else{$dirsize +=filesize ($file); }}} closedir ($dir); return $dirsize; }?>
The above describes the PHP implementation of the statistical directory file size function, including the content, I hope the PHP tutorial interested in a friend helpful.