Generate a human friendly, readable file size from a number value.
<?php
/**
* Takes a humanized value of size.
*
* @static
* @access public
* @param int $fileSize
* @param array $options
* @return string
* @links http://en.wikipedia.org/wiki/Units_of_information
*/
function humanizeSize($fileSize, $options = array())
{
isset($options['unit']) || $options['unit'] = 'byte';
isset($options['standard']) || $options['standard'] = 'si';
isset($options['width']) || $options['width'] = 'narrow';
isset($options['prefix']) || $options['prefix'] = ' ';
isset($options['round']) || $options['round'] = 2;
$options['units'] = array(
'byte' => array(
'singular' => array(
'narrow' => 'B',
'wide' => 'byte'
),
'plural' => array(
'narrow' => 'B',
'wide' => 'bytes'
)
),
'bit' => array(
'singular' => array(
'narrow' => 'bit',
'wide' => 'bit'
),
'plural' => array(
'narrow' => 'bits',
'wide' => 'bits'
)
)
);
$options['standards'] = array(
'si' => array(
'narrow' => array(
"",
"k",
"M",
"G",
"T",
"P",
"E",
"Z",
"Y"
),
'wide' => array(
"",
"kilo",
"mega",
"giga",
"tera",
"peta",
"exa",
"zetta",
"yotta"
)
),
'iec' => array(
'narrow' => array(
"",
"Ki",
"Mi",
"Gi",
"Ti",
"Pi",
"Ei",
"Zi",
"Yi"
),
'wide' => array(
"",
"kibi",
"mebi",
"gibi",
"tebi",
"pebi",
"exbi",
"zebi",
"yobi"
)
)
);
switch ($options['unit'] = strtolower($options['unit'])) {
case 'bit':
case 'bits':
case 'b':
$options['unit'] = 'bit';
break;
default:
$options['unit'] = 'byte';
}
switch ($options['standard'] = strtolower($options['standard'])) {
case 'i':
case 'iec':
$options['standard'] = 'iec';
break;
default:
$options['standard'] = 'si';
}
switch ($options['width'] = strtolower($options['width'])) {
case 'w':
case 'wide':
$options['width'] = 'wide';
break;
default:
$options['width'] = 'narrow';
}
$factor = ($options['standard'] == 'si') ? 1000 : 1024;
$i = 0;
if ($options['unit'] == 'bit') {
$fileSize *= 8;
}
while ($fileSize > $factor) {
$fileSize /= $factor;
$i++;
}
$fileSize = round($fileSize, $options['round']);
$n = $fileSize == 0 || $fileSize == 1 ? 'singular' : 'plural';
$humanizeSize = $fileSize . $options['prefix'] . $options['standards'][$options['standard']][$options['width']][$i] . $options['units'][$options['unit']][$n][$options['width']];
return $humanizeSize;
}
// example usage
// -------------
$file = 'myisofile.iso';
$file_size_as_bytes = filesize($file);
echo 'File: ' . $file . "n";
echo 'Bytes: ' . $file_size_as_bytes . "n";
$friendly = humanizeSize($file_size_as_bytes);
echo 'Humanized: ' . $friendly;
// output...
// File: myisofile.iso
// Bytes: 637597696
// Humanized: 637.6 MB
?>