Learning never exhausts the mind

Published on by

This function will format a given number into a pretty file size, for example, convert 1000000 to 1MB, 3523 to 3k and so on.
function formatbytes($val, $digits = 3, $mode = "SI", $bB = "B")
  $si = array("", "k", "M", "G", "T", "P", "E", "Z", "Y");
  $iec = array("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi");

      case "SI" : $factor = 1000; $symbols = $si; break;
      case "IEC" : $factor = 1024; $symbols = $iec; break;
      default : $factor = 1000; $symbols = $si; break;

      case "b" : $val *= 8; break;
      default : $bB = "B"; break;
  for($i=0;$i<count($symbols)-1 && $val>=$factor;$i++)
      $val /= $factor;
  $p = strpos($val, ".");
  if($p !== false && $p > $digits) 
    $val = round($val);
  elseif($p !== false) 
    $val = round($val, $digits-$p);
  return round($val, $digits) . " " . $symbols[$i] . $bB;

Simply pass in an integer file size and it will return a value to 3 significant figures using SI notation. You can increase the number of figures by changing the second parameter in the call and the mode in the last two.

$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

Will output "somefile.txt: 219543 bytes"

$filename = 'somefile.txt';
echo $filename . ': ' . formatbytes(filesize($filename));

Will output "somefile.txt: 219 kB"

I did not write this function, but I have been using it for years. I do not know who the original author is, but if you know please let me know so I can give credit.

I also have a similar function for ASP.Net and C# which pretty formats file size.

Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.