Craig Francis


PHP Human File Size

If you want to convert a file-size from bytes to a human readable format, then you can use this function...

function fileSize2human($size) {

$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
foreach ($units as $unit) {
if ($size >= 1024 && $unit != 'YB') {
$size = ($size / 1024);
} else {
return round($size, 0) . $unit;
}
}
}

And for an example the its usage...

echo fileSize2human(30);
// OUTPUT: 30B

echo fileSize2human(1256);
// OUTPUT: 1KB

echo fileSize2human(12502111116);
// OUTPUT: 12GB

echo fileSize2human(filesize('index.php'));
// OUTPUT: 3KB

Any feedback would be greatly appreciated. If you would like to use this code, please read the licence it is released under.