diff options
author | Kevin Mandura <webmaster@kevin-mandura.de> | 2024-03-11 00:49:08 +0100 |
---|---|---|
committer | Kevin Mandura <webmaster@kevin-mandura.de> | 2024-03-11 00:49:08 +0100 |
commit | 7364b0a6a91bd28dca0a7b20c4ef505686521fca (patch) | |
tree | 4eeecc24bb7b1b3cc4dc49b8590ecf6d332b3d9a | |
parent | 1ea44a84a54d421cd157d6fcac0165e4505672de (diff) | |
download | ktls-website-7364b0a6a91bd28dca0a7b20c4ef505686521fca.tar.gz ktls-website-7364b0a6a91bd28dca0a7b20c4ef505686521fca.zip |
Add humanFilesize function
-rw-r--r-- | includes/functions/humanFilesize.inc.php | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/includes/functions/humanFilesize.inc.php b/includes/functions/humanFilesize.inc.php new file mode 100644 index 0000000..d7a5de0 --- /dev/null +++ b/includes/functions/humanFilesize.inc.php @@ -0,0 +1,38 @@ +<?php + +/** + * + * Convert bytes to human readable filesize + * + * From a raw bytes number, this function returns a formatted string with the + * converted unit. + * + * @author Kevin Mandura <webmaster@kevin-mandura.de> + * @license GPL + * @param int $bytes Input bytes + * @param int $decimals Optional, amount of decimal places for output format + * @return string Formatted human readable filesize + * + * @copyright Copyright (c) 2024, Kevin Mandura <webmaster@kevin-mandura.de> + */ +function humanFilesize(int $bytes, ?int $decimals = 2):string { + $sizes = 'BKMGTP'; + $factor = floor((strlen($bytes) - 1) / 3); + + $result = sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sizes[(int)$factor]; + + if (strpos($result, 'B') !== false) + $result = str_replace("B", "Bytes", $result); + else if (strpos($result, 'K') !== false) + $result = str_replace("K", "KiB", $result); + else if (strpos($result, 'M') !== false) + $result = str_replace("M", "MiB", $result); + else if (strpos($result, 'G') !== false) + $result = str_replace("G", "GiB", $result); + else if (strpos($result, 'T') !== false) + $result = str_replace("T", "TiB", $result); + else if (strpos($result, 'P') !== false) + $result = str_replace("P", "PiB", $result); + + return $result; +} |