Skip to content

Instantly share code, notes, and snippets.

@LouisLandry
Created October 5, 2012 20:18
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 LouisLandry/3842129 to your computer and use it in GitHub Desktop.
Save LouisLandry/3842129 to your computer and use it in GitHub Desktop.
Quick function to make byte size human readable.
/**
* Convert bytes to human readable format.
*
* @param integer bytes Size in bytes to convert
*
* @return string
*/
function bytesToSize($bytes, $precision = 2)
{
$kilobyte = 1024;
$megabyte = $kilobyte * 1024;
$gigabyte = $megabyte * 1024;
$terabyte = $gigabyte * 1024;
if (($bytes >= 0) && ($bytes < $kilobyte)) {
return $bytes . ' B';
} elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) {
return round($bytes / $kilobyte, $precision) . ' KB';
} elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) {
return round($bytes / $megabyte, $precision) . ' MB';
} elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) {
return round($bytes / $gigabyte, $precision) . ' GB';
} elseif ($bytes >= $terabyte) {
return round($bytes / $terabyte, $precision) . ' TB';
} else {
return $bytes . ' B';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment