Skip to content

Instantly share code, notes, and snippets.

@ismaail
Last active June 28, 2023 14:26
Show Gist options
  • Save ismaail/6193267 to your computer and use it in GitHub Desktop.
Save ismaail/6193267 to your computer and use it in GitHub Desktop.
File size
<?php
/**
* Convert file size in bytes to nice (human-readable) format.
* This snippet shows you how to convert file size in bytes to nice (human-readable) format in PHP.
* If the size is less than 1 MB, show the size in KB, if it's between 1 MB - 1 GB show it in MB, etc.
*/
function sizeForHuman(int $value, int $decimal = 0): string
{
$units = ['', 'K', 'M', 'B', 'T'];
// $units = ['B', 'KB', 'MB', 'GB', 'TB'];
$power = $value > 0 ? floor(log($value, 1024)) : 0;
return number_format($value / (1024 ** $power), $decimal) . $units[$power];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment