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.
The convert_filesize() function converts file size to KB, MB, GB, TB, PB, EB, ZB, and YB using PHP.
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);
Hi,
thanks for the example. I’ve noticed that strlen() is not a good method for determining factor because big numbers get converted to float automatically in PHPP. I suggest replacing the line with:
factor = floor(log($bytes, 1024));
Other than that, it works fine.
Cheers, Pavel