Web Design that taps into the haromny and vision of your dreams.

Format a Number as File Size in PHP

Using PHP to format a file size

Written By on in PHP

284 words, estimated reading time 2 minutes.

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");
 
  switch(strtoupper($mode)) 
  {
      case "SI" : $factor = 1000; $symbols = $si; break;
      case "IEC" : $factor = 1024; $symbols = $iec; break;
      default : $factor = 1000; $symbols = $si; break;
  }
 
  switch($bB) 
  {
      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.

Examples:

$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.

Last updated on: Thursday 22nd June 2017

 

Comments

There are no comments for this post. Be the first!

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me