Skip to content

Instantly share code, notes, and snippets.

@fernandovaller
Created May 26, 2017 13:50
Show Gist options
  • Save fernandovaller/8994414fb80ada7c44bb90561e24d154 to your computer and use it in GitHub Desktop.
Save fernandovaller/8994414fb80ada7c44bb90561e24d154 to your computer and use it in GitHub Desktop.
<?php
function size($size, $precision = 2){
$base = log($size, 1024);
//$suffixes = array('', 'K', 'M', 'G', 'T');
$suffixes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
return round(pow(1024, $base - floor($base)), $precision) .' '. $suffixes[floor($base)];
}
function bytes($bytes, $force_unit = NULL, $format = NULL, $si = TRUE)
{
// Format string
$format = ($format === NULL) ? '%01.2f %s' : (string) $format;
// IEC prefixes (binary)
if ($si == FALSE OR strpos($force_unit, 'i') !== FALSE)
{
$units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
$mod = 1024;
}
// SI prefixes (decimal)
else
{
$units = array('B', 'kB', 'MB', 'GB', 'TB', 'PB');
$mod = 1000;
}
// Determine unit to use
if (($power = array_search((string) $force_unit, $units)) === FALSE)
{
$power = ($bytes > 0) ? floor(log($bytes, $mod)) : 0;
}
return sprintf($format, $bytes / pow($mod, $power), $units[$power]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment