Work Out Real File Sizes With PHP

Displaying the size of a file in bytes is all well and good, but means little to most people so converting the size into something a little more readable is a must. The following function will take the number of bytes that a file is and convert it into something a little more meaningful. Rather than just convert the value into kilobytes it returns the largest denomination of size. So if your file is greater than 1073741824 bytes the function will return your value in gigabytes.

function readableFileSize($size){
 $size = $size-1;
 if($size >= 1099511627776){
  return number_format(($size / 1099511627776),2) . ' TB';
 }elseif($size >= 1073741824){
  return number_format(($size / 1073741824),2) . ' GB';
 }elseif($size >= 1048576){
  return number_format(($size / 1048576),2) . ' MB';
 }elseif($size >= 1024){
  return number_format(($size / 1024),2) . ' KB';
 }elseif($size > 0){
  return $size . ' b';
 }elseif($size == 0 || $size == -1){
  return '0 b';
 }
}

Here are some examples of it in action.

echo readableFileSize(512); // 511 b
echo readableFileSize(3793); // 3.70 KB
echo readableFileSize(456765); // 446.06 KB
echo readableFileSize(5000000); // 4.77 MB
echo readableFileSize(123456789); // 117.74 MB
echo readableFileSize(648564967358); // 604.02 GB

This function comes in handy when telling users the maximum size of file they can upload. As this is probably set as a variable in bytes in your script you can't just print it out to users as they will have to work this out for themselves.

Update

I recently found a very neat way of doing this using a single loop. It is slightly more processor intensive than the original version, but it works by continuously dividing the size by 1024 until it is less than 1024. The number of times this is done is then used to figure out the units.

function readableFileSize($size){
 $units = array(' B', ' KB', ' MB', ' GB', ' TB');
 for($i = 0; $size > 1024; $i++){
  $size /= 1024;
 }
 return round($size, 2).$units[$i];
}

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
8 + 9 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.