Skip to content

Instantly share code, notes, and snippets.

@gonejack
Created December 4, 2015 14:28
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 gonejack/e6a9e2a481be09071335 to your computer and use it in GitHub Desktop.
Save gonejack/e6a9e2a481be09071335 to your computer and use it in GitHub Desktop.
<?php
/**
* 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