Skip to content

Instantly share code, notes, and snippets.

@EarMaster
Last active June 19, 2019 10:56
Show Gist options
  • Save EarMaster/da9b2360867f6df12868 to your computer and use it in GitHub Desktop.
Save EarMaster/da9b2360867f6df12868 to your computer and use it in GitHub Desktop.
Formats a filesize into a human readable format. First parameter is filesize in bytes, second parameter is the precision of the resulting float and the last parameter is the system (choose between 'decimal' aka SI-based or 'binary' based calculation).
<?php
function format_filesize($size, $decimals=1, $system='decimal') {
$size = intval($size);
$fileSizes = array(
'decimal' => array('Byte', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'),
'binary' => array('Byte', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB')
);
for ($n=0; $size>($system=='decimal'?1000:1024); $n++)
$size = $size/($system=='decimal'?1000:1024);
return round($size, $decimals).' '.$fileSizes[$system][$n];
};
@EarMaster
Copy link
Author

@EarMaster
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment