Skip to content

Instantly share code, notes, and snippets.

@DevWael
Created November 18, 2018 20:16
Show Gist options
  • Select an option

  • Save DevWael/b7e4831580b43075d09389eb15b5e95b to your computer and use it in GitHub Desktop.

Select an option

Save DevWael/b7e4831580b43075d09389eb15b5e95b to your computer and use it in GitHub Desktop.
Convert bytes to human readable format
<?php
/**
* Convert bytes to human readable format
*
* @param integer $bytes Size in bytes to convert
* @param integer $precision
*
* @return string
*/
function prefix_human_bytes( $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