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

问题描述 投票:-2回答:4

我试着把这个字节变成千兆字节的图像主机请帮忙,谢谢你,抱歉英文不好:

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>" ;
php
4个回答
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


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

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];
}

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';
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.