Created
July 21, 2015 10:17
-
-
Save davidthingsaker/ff5366b8ae8def45a8c3 to your computer and use it in GitHub Desktop.
Human readable data sizes in PHP
This file contains 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
# Pass in the level of accuracy and optionally if you are talking about speed. Which will add a per seconds suffux. | |
public static function human_datasize($bytes, $decimals = 2, $speed = false) | |
{ | |
$sz = 'BKMGTP'; | |
if(is_null($bytes)) { | |
return 'Unlimited'; | |
} | |
if ($speed) { | |
$suffix = 'bps'; | |
} else { | |
$suffix = 'B'; | |
} | |
$factor = floor((strlen($bytes) - 1) / 3); | |
$str = sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor]; | |
if(substr($str, -1) !== 'B') { | |
$str = $str . $suffix; | |
} | |
return $str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment