以GB为单位转换php disk_total_space()的输出

时间:2016-07-07 06:06:50

标签: php

我从我的项目获得了这个代码片段,它获取了我指定磁盘中的可用空间,所以这里是

$ds = disk_total_space(substr(base_path(), 0, 2));
$fs = disk_free_space(substr(base_path(), 0, 2));

所以我需要做的就是以GB的形式返回任何想法我可以做到这一点吗?非常感谢!

更新 我找到了这个代码,它将字节转换为不同的格式

if ($ds >= 1073741824)
    {
        $ds = number_format($ds / 1073741824, 2) . ' GB';
    }
    elseif ($ds >= 1048576)
    {
        $ds = number_format($ds / 1048576, 2) . ' MB';
    }
    elseif ($ds >= 1024)
    {
        $ds = number_format($ds / 1024, 2) . ' KB';
    }
    elseif ($ds > 1)
    {
        $ds = $ds . ' B';
    }
    elseif ($ds == 1)
    {
        $ds = $ds . ' B';
    }
    else
    {
        $ds = '0 size';
    }

关于我如何只能将它变成GB的任何想法?

1 个答案:

答案 0 :(得分:1)

我使用了这个功能:)

private function convGB($bytes, $unit = "", $decimals = 2)
{
     $units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 
     'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);

     $value = 0;
     if ($bytes > 0) 
     {
         if (!array_key_exists($unit, $units)) 
         {
             $pow = floor(log($bytes)/log(1024));
             $unit = array_search($pow, $units);
         }

         $value = ($bytes/pow(1024,floor($units[$unit])));
     }

     if (!is_numeric($decimals) || $decimals < 0) {
     $decimals = 2;
     }

     return sprintf('%.' . $decimals . 'f '.$unit, $value);
}

将其称为convGB(*bytes in here*);