-2

I am try to make this bytes into gigabytes for image host please help and thanks you, sorry for bad english:

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>" ;
selnotrab
  • 13
  • 1
  • 4

4 Answers4

5
echo "" . $sample[0]/(1024*1024*1024) . " total space used </br>" ;
DeweyOx
  • 719
  • 5
  • 14
  • Could you please clarify why that empty `""` is needed here? I personally see no reason why would one start with that, instead of just doing `echo $sample[0]...` – David Feb 26 '18 at 03:40
1

I personally prefer one simple, yet elegant solution:

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];
}
David
  • 490
  • 2
  • 10
0

This should automatically determine the best unit. I can show you how to force it to use GB at all times if you wish.

Add this to your code:

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

Test it:

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

Source: https://stackoverflow.com/a/8348396/1136832

Community
  • 1
  • 1
Martyn
  • 46
  • 4
  • explode AND a global, really ? With the same success you can just insert the units inside the function, and write an array directly, instead of writing a string and then converting it to an array. Far better would be if instead of `global $units;` you do `$units=array('B','KB','MB','GB','TB','PB');` – David Feb 26 '18 at 03:39
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';
    }
}
Faisal Ahmed
  • 350
  • 3
  • 7