Let I take an example to explain it which I expect. Example: I have file size '3147483648 Bytes', and I want to convert it to following appropriate file size: 2 GB + 70 MB + 333 KB + 512 Bytes.
Any help is appreciated.
Let I take an example to explain it which I expect. Example: I have file size '3147483648 Bytes', and I want to convert it to following appropriate file size: 2 GB + 70 MB + 333 KB + 512 Bytes.
Any help is appreciated.
You can write your own function for that: Something like
bytes = filesize % 1024;
filesize = (int)(filesize / 1024);
kbytes = filesize % 1024;
filesize = (int)(filesize / 1024);
and so on...
I have found the solution. I don't really like how it used recursion, but it get what I want.
function shortenBytes($sizeInBytes){
    $units = array('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB' , 'EB', 'ZB', 'YB');
    $resultArray = array(
        'YB' => 0,'ZB' => 0,'EB' => 0,'PB' => 0,'TB' => 0,
        'GB' => 0,'MB' => 0,'KB' => 0,'Bytes' => 0);
    $remainder = $sizeInBytes;
    $i = count($units);
    while($i >= 0)
    {
        $pownumber = pow(1024, $i);
        if($sizeInBytes >= $pownumber){
            $resultArray[$units[$i]] = (int)($sizeInBytes / $pownumber);
            $remainder = abs($sizeInBytes % $pownumber);
            $i--;
            $remainder = recursiveGetUnitArray($remainder,$i,$resultArray);
        }
        $sizeInBytes = $remainder;
        $i--;
    }
    return $resultArray;
}
function recursiveGetUnitArray($sizeInBytes, $i, &$resultArray){
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB' , 'EB', 'ZB', 'YB');
    $remainder = $sizeInBytes;
    $pownumber = pow(1024, $i);
    if($sizeInBytes >= $pownumber){
        $resultArray[$units[$i]] = (int)($sizeInBytes / $pownumber);
        $remainder = abs($sizeInBytes % $pownumber);
        $i--;
        $remainder = recursiveGetUnitArray($remainder,$i,$resultArray);
    }
    return $remainder;
}
The result of shortenBytes(3147483648);
            array (size=9)
              'YB' => int 0
              'ZB' => int 0
              'EB' => int 0
              'PB' => int 0
              'TB' => int 0
              'GB' => int 2
              'MB' => int 70
              'KB' => int 333
              'Bytes' => int 512
See official php.net website :
<?php
function human_filesize($bytes, $decimals = 2) {
  $sz = 'BKMGTP';
  $factor = floor((strlen($bytes) - 1) / 3);
  return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
?>