How to Convert File Size to Human Readable Format in PHP

Human readable file size makes easier to read the file size and converts a number of bytes in the largest unit. To display file size in human readable format, you need to convert it to KB, MB, GB, TB, etc. Generally, the file size is stored in bytes which can be easily converted to kilobyte, megabyte, gigabyte, etc format.

You can easily convert file size in any human readable unit using PHP. The following code snippet shows you how to convert bytes in KB, MB, GB, TB, PB, EB, ZB, and YB using PHP. For better usability, all the PHP code are grouped in convert_filesize() function.

File Size Conversion with PHP

The convert_filesize() function converts file size to KB, MB, GB, TB, PB, EB, ZB, and YB using PHP.

  • $bytes – Specify file size in bytes.
  • $decimals – Specify the number of decimal places. Default 2.
function convert_filesize($bytes$decimals 2){
    
$size = array('B','kB','MB','GB','TB','PB','EB','ZB','YB');
    
$factor floor((strlen($bytes) - 1) / 3);
    return 
sprintf("%.{$decimals}f"$bytes pow(1024$factor)) . @$size[$factor];
}

Usage
Call the convert_filesize() function and pass the filesize in bytes.

// Get file size
$size filesize('backup.zip');

// Convert file size
echo convert_filesize($size);

1 Comment

  1. Pavel Zak Said...

Leave a reply

keyboard_double_arrow_up