PHP:将字节转换为GB(文件夹大小)

时间:2013-05-16 01:04:11

标签: php

我尝试将此字节设为千兆字节用于图像主机请帮助并感谢您,对不起英语不好:

function foldersize($dir){
 $count_size = 0;
 $count = 0;
 $dir_array = scandir($dir);
 foreach($dir_array as $key=>$filename){
  if($filename!=".." && $filename!="."){
   if(is_dir($dir."/".$filename)){
    $new_foldersize = foldersize($dir."/".$filename);
    $count_size = $count_size + $new_foldersize[0];
    $count = $count + $new_foldersize[1];
   }else if(is_file($dir."/".$filename)){
    $count_size = $count_size + filesize($dir."/".$filename);
    $count++;
   }
  }

 }

 return array($count_size,$count);
}

$sample = foldersize("images");

echo "" . $sample[1] . " images hosted " ;
echo "" . $sample[0] . " total space used </br>" ;

4 个答案:

答案 0 :(得分:4)

echo "" . $sample[0]/(1024*1024*1024) . " total space used </br>" ;

答案 1 :(得分:1)

我个人更喜欢一个简单而优雅的解决方案:

function formatSize($bytes,$decimals=2){
    $size=array('B','KB','MB','GB','TB','PB','EB','ZB','YB');
    $factor=floor((strlen($bytes)-1)/3);
    return sprintf("%.{$decimals}f",$bytes/pow(1024,$factor)).@$size[$factor];
}

答案 2 :(得分:0)

这应该自动确定最佳单位。如果您愿意,我可以告诉您如何强制它始终使用GB。

将此添加到您的代码中:

$units = explode(' ', 'B KB MB GB TB PB');

function format_size($size) {
    global $units;

    $mod = 1024;

    for ($i = 0; $size > $mod; $i++) {
        $size /= $mod;
    }

    $endIndex = strpos($size, ".")+3;

    return substr( $size, 0, $endIndex).' '.$units[$i];
}

测试它:

echo "" . $sample[1] . " images hosted " ;
echo "" . format_size($sample[0]) . " total space used </br>" 

来源:https://stackoverflow.com/a/8348396/1136832

答案 3 :(得分:0)

function convertFromBytes($bytes)
{
    $bytes /= 1024;
    if ($bytes >= 1024 * 1024) {
        $bytes /= 1024;
        return number_format($bytes / 1024, 1) . ' GB';
    } elseif($bytes >= 1024 && $bytes < 1024 * 1024) {
        return number_format($bytes / 1024, 1) . ' MB';
    } else {
        return number_format($bytes, 1) . ' KB';
    }
}