human readable file size

前端 未结 11 2229
梦毁少年i
梦毁少年i 2020-12-25 10:48
function humanFileSize($size)
{
    if ($size >= 1073741824) {
      $fileSize = round($size / 1024 / 1024 / 1024,1) . \'GB\';
    } elseif ($size >= 1048576)          


        
11条回答
  •  温柔的废话
    2020-12-25 11:47

    Here is a working function managing till Yottabyte:

    function DisplayFileSize($size, $unit = false, $precision = 2){
    
    $b = $size;
    $kb = round($size / 1024, $precision);
    $mb = round($kb / 1024, $precision);
    $gb = round($mb / 1024, $precision);
    $tb = round($gb / 1024, $precision);
    $pb = round($tb / 1024, $precision);
    $eb = round($pb / 1024, $precision);
    $zb = round($eb / 1024, $precision);
    $yb = round($zb / 1024, $precision);
    
    if((!$unit && floor($kb) == 0) || $unit == "b") {
        return array("value" => FormatNumber($b), "unit" => "bytes");
    } else if((!$unit && floor($mb) == 0) || $unit == "kb") {
        return array("value" => FormatNumber($kb, 2), "unit" => "Kb");
    } else if((!$unit && floor($gb) == 0) || $unit == "mb") {
        return array("value" => FormatNumber($mb, 2), "unit" => "Mb");
     } else if((!$unit && floor($tb) == 0) || $unit == "gb") {
         return array("value" => FormatNumber($gb, 2), "unit" => "Gb");
     } else if((!$unit && floor($pb) == 0) || $unit == "tb") {
         return array("value" => FormatNumber($tb, 2), "unit" => "Tb");
     } else if((!$unit && floor($eb) == 0) || $unit == "pb") {
        return array("value" => FormatNumber($pb, 2), "unit" => "Pb");
     } else if((!$unit && floor($zb) == 0) || $unit == "eb") {
         return array("value" => FormatNumber($eb, 2), "unit" => "Eb");
     } else if((!$unit && floor($yb) == 0) || $unit == "zb") {
         return array("value" => FormatNumber($zb, 2), "unit" => "Zb");
    } else {
        return array("value" => FormatNumber($yb, 2), "unit" => "Yb");
    }
    

    }

提交回复
热议问题