Skip to content

Instantly share code, notes, and snippets.

@cp6
Created July 2, 2020 01:12
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 cp6/da66f142efaed74dd7f16ae6f586cf19 to your computer and use it in GitHub Desktop.
Save cp6/da66f142efaed74dd7f16ae6f586cf19 to your computer and use it in GitHub Desktop.
PHP convert and format bytes function
<?php
function convertBytes(int $bytes, string $convert_to = 'KB', bool $format = true, int $decimals = 2): float
{
if ($convert_to == 'KB') {
$value = ($bytes / 1024);
} elseif ($convert_to == 'MB') {
$value = ($bytes / 1048576);
} elseif ($convert_to == 'GB') {
$value = ($bytes / 1073741824);
} elseif ($convert_to == 'TB') {
$value = ($bytes / 1099511627776);
} else {
$value = $bytes;
}
if ($format) $value = number_format($value, $decimals);
return $value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment