Say you were displaying the size of a file in PHP. You obviously get the file size in Bytes by using filesize().

You won’t have any idea what the file size is if you read it in Bytes. Bytes is useful for file transmission in a network, but not for human usage. So, it’s better to convert it to human readable form.

The circled areas show the converted size from Bytes. App - Lobby Downloader
The circled areas show the converted size from Bytes. App – Lobby Downloader

Here is a simple function to convert Bytes to KBMBGBTB :

function convertToReadableSize($size){
  $base = log($size) / log(1024);
  $suffix = array("", "KB", "MB", "GB", "TB");
  $f_base = floor($base);
  return round(pow(1024, $base - floor($base)), 1) . $suffix[$f_base];
}

Note that KB is for Kibibyte. Normal systems uses Kilobyte (1000). If you want to change it, then replace the parameter passed to log().

Note that upto TB is included in the function. You can extend it by adding more into the $suffix array.

Usage

Just call the function :

echo convertToReadableSize(1024); // Outputs '1KB'
echo convertToReadableSize(1024 * 1024); // Outputs '1MB'
echo convertToReadableSize(filesize("/home/simsu/good.txt"));

I had to use it for a download manager app I created for Lobby. You can see the source code of “Downloader” app here.