Created
November 18, 2018 20:16
-
-
Save DevWael/b7e4831580b43075d09389eb15b5e95b to your computer and use it in GitHub Desktop.
Convert bytes to human readable format
This file contains hidden or 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 | |
| /** | |
| * 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