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

Format a Number as File Size in PHP

By on in Coding

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");
      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.

Last updated on: Thursday 22nd June 2017



Have a question or suggestion? Please leave a comment to start the discussion.


Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.