Last active
October 7, 2023 11:19
-
-
Save nagiyevelchin/0574e26201833a7ddb1908f5dcc79d4a to your computer and use it in GitHub Desktop.
This PHP code defines a function called humanlyFileSize that is used to convert a file size in bytes into a human-readable format with size suffixes (e.g., KB, MB, GB).
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 | |
// Define a function named humanlyFileSize that takes two parameters: | |
// $bytes - the file size in bytes | |
// $decimals (optional) - the number of decimal places to include in the result (default is 2) | |
function humanlyFileSize($bytes, $decimals = 2) { | |
// Define a string $sz containing the size suffixes for bytes (B), kilobytes (K), megabytes (M), | |
// gigabytes (G), terabytes (T), and petabytes (P). | |
$sz = 'BKMGTP'; | |
// Calculate the appropriate size suffix based on the file size in bytes. | |
// The $factor represents the position of the size suffix in the $sz string. | |
$factor = floor((strlen($bytes) - 1) / 3); | |
// Calculate the human-readable file size by dividing $bytes by the appropriate power of 1024 | |
// and formatting the result with the specified number of decimals. | |
// The @ symbol is used to suppress any potential warnings if $factor is out of range. | |
// For example, if $bytes is very small, $factor might be negative, leading to a warning. | |
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment