PHP文件大小格式化函数合集(2)

/**
  * 文件大小格式化
  * @param type $filesize
  */
private function sizeCount($filesize)
{
    if ($filesize >= 1073741824) {
        $filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
    }

    else if ($filesize >= 1048576) {
        $filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
    }

    else if ($filesize >= 1024) {
        $filesize = round($filesize / 1024 * 100) / 100 . ' KB';
    }

return $filesize;
}


//该函数最主要的是根据文件的字节数,判断应当选择的统计单位,也就是说一个文件用某一单位比如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;
}
//辅助函数 round_up(),该函数用来取舍小数点位数的,四舍五入。
function round_dp($num , $dp)
{
  $sh = pow(10 , $dp);
  return (round($num*$sh)/$sh);
}

这样我们就能很好额统计任何一个文件的大小了,首先通过系统自带的filesize()函数获得文件的字节数,再用上面的这些函数换算成适当的单位就可以了

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/1c0290818b94a2a89157a9f0d4d9572f.html