Skip to content

Instantly share code, notes, and snippets.

@Debashis-Sinha
Last active July 16, 2017 07:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Debashis-Sinha/254003644485433d095777637d2e7293 to your computer and use it in GitHub Desktop.
Save Debashis-Sinha/254003644485433d095777637d2e7293 to your computer and use it in GitHub Desktop.
php get file size from byte
/**
* @param $bytes
* @param string $unit
* @param int $decimals
* @return string
*/
static function sizeFormat($bytes, $unit = "", $decimals = 2)
{
$units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);
$value = 0;
if ($bytes > 0) {
if (!array_key_exists($unit, $units)) {
$pow = floor(log($bytes)/log(1024));
$unit = array_search($pow, $units);
}
$value = ($bytes/pow(1024,floor($units[$unit])));
}
if (!is_numeric($decimals) || $decimals < 0) {
$decimals = 2;
}
return sprintf('%.' . $decimals . 'f '.$unit, $value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment