Created
November 6, 2014 12:10
-
-
Save richjenks/7016d3c6e6bab65fa06e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* filesize | |
* | |
* Formats a filesize into a human-readable format | |
* | |
* Usage: | |
* <code> | |
* filesize(50, false, '{size} <small>{unit}</small'); | |
* </code> | |
* | |
* @param int $size Filesize in bytes | |
* @param int $precision Number of decimal places to round to | |
* @param string $format Output format with placeholders "{size}" and "{unit}" | |
* | |
* @return string Formatted filesize | |
*/ | |
public static function filesize($size, $precision = 0, $format = '{size} {unit}') { | |
// If size is zero, skip the calculations | |
if ($size !== 0) { | |
// Calculate base | |
$base = log($size) / log(1024); | |
// Array of units | |
$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); | |
// Calculate size | |
$size = round(pow(1024, $base - floor($base)), $precision); | |
// Select unit | |
$unit = $units[floor($base)]; | |
} else { | |
// Size is zero so hardcode unit | |
$unit = 'B'; | |
} | |
// Construct output as per format | |
$format = str_replace('{size}', $size, $format); | |
$format = str_replace('{unit}', $unit, $format); | |
return $format; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment