计算文件夹的大小,包括子文件夹,格式化输出文件夹大小、文件数、子文件夹数信息。
代码如下 |
复制代码 |
//代码也可以用于统计目录数
//格式化输出目录大小 单位:Bytes,KB,MB,GB
function getDirectorySize($path)
{
$totalsize = 0;
$totalcount = 0;
$dircount = 0;
if ($handle = opendir ($path))
{
while (false !== ($file = readdir($handle)))
{
$nextpath = $path . '/' . $file;
if ($file != '.' && $file != '..' && !is_link ($nextpath))
{
if (is_dir ($nextpath))
{
$dircount++;
$result = getDirectorySize($nextpath);
$totalsize += $result['size'];
$totalcount += $result['count'];
$dircount += $result['dircount'];
}
elseif (is_file ($nextpath))
{
$totalsize += filesize ($nextpath);
$totalcount++;
}
}
}
}
closedir ($handle);
$total['size'] = $totalsize;
$total['count'] = $totalcount;
$total['dircount'] = $dircount;
return $total;
}
|
PHP中计算文件目录大小其实主要是用到"filesize"函数,通过递归的方法计算每个文件的大小,再计算他们的和即是整个文件目录的大小。
因为直接返回的文件大小是以字节为单位的,所以我们一般还要经过换算得到我们常见得大小,以下是单位换算的函数:
代码如下 |
复制代码 |
function sizeFormat($size)
{
$sizeStr='';
if($size<1024)
{
return $size." bytes";
}
else if($size<(1024*1024))
{
$size=round($size/1024,1);
return $size." KB";
}
else if($size<(1024*1024*1024))
{
$size=round($size/(1024*1024),1);
return $size." MB";
}
else
{
$size=round($size/(1024*1024*1024),1);
return $size." GB";
}
}
$path="/home/www/htdocs";
$ar=getDirectorySize($path);
echo "路径 : $path";
echo "目录大小 : ".sizeFormat($ar['size'])." ";
echo "文件数 : ".$ar['count']." ";
echo "目录术 : ".$ar['dircount']." ";
//print_r($ar);
?> |
后面附一个单位函数
该函数最主要的是根据文件的字节数,判断应当选择的统计单位,也就是说一个文件用某一单位比如MB,那么该文件肯定小于1GB,否则当然要用GB作为单位了,而且文件要大于KB,不然的话得用更小的单位统计。该函数代码如下
代码如下 |
复制代码 |
//size() 统计文件大小
function size($byte)
{
if($byte < 1024) {
$unit="B";
}
else if($byte < 10240) {
$byte=round_dp($byte/1024, 2);
$unit="KB";
}
else if($byte < 102400) {
$byte=round_dp($byte/1024, 2);
$unit="KB";
}
else if($byte < 1048576) {
$byte=round_dp($byte/1024, 2);
$unit="KB";
}
else if ($byte < 10485760) {
$byte=round_dp($byte/1048576, 2);
$unit="MB";
}
else if ($byte < 104857600) {
$byte=round_dp($byte/1048576,2);
$unit="MB";
}
else if ($byte < 1073741824) {
$byte=round_dp($byte/1048576, 2);
$unit="MB";
}
else {
$byte=round_dp($byte/1073741824, 2);
$unit="GB";
}
$byte .= $unit;
return $byte;
}
function round_dp($num , $dp)
{
$sh = pow(10 , $dp);
return (round($num*$sh)/$sh);
}
|
关于php round函数用法可参考 http://www.111com.net/w3school/php/func_math_round.htm