Phobos Posté(e) le 10 décembre 2014 Signaler Share Posté(e) le 10 décembre 2014 Fonction PHP simple qui formate les octets à la forme désirée. Byte (Kilobyte (KB) Megabyte (MB) Gigabyte (GB) Terabyte (TB) Petabyte (PB) Exabyte (EB) Zettabyte (ZB) Yottabyte (YB) Fonction prend trois paramètres : (octets obligatoires, unité optionnelle, décimale optionnelle) <?php function byteFormat($bytes, $unit = "", $decimals = 2) { $units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8); $value = 0; if ($bytes > 0) { // Generate automatic prefix by bytes // If wrong prefix given if (!array_key_exists($unit, $units)) { $pow = floor(log($bytes)/log(1024)); $unit = array_search($pow, $units); } // Calculate byte value by prefix $value = ($bytes/pow(1024,floor($units[$unit]))); } // If decimals is not numeric or decimals is less than 0 // then set default value if (!is_numeric($decimals) || $decimals < 0) { $decimals = 2; } // Format output return sprintf('%.' . $decimals . 'f '.$unit, $value); } ?> Exemple d'utilisation echo byteFormat(4096, "B"); echo byteFormat(8, "B", 2); echo byteFormat(1, "KB", 5); echo byteFormat(1073741824, "B", 0); echo byteFormat(1073741824, "KB", 0); echo byteFormat(1073741824, "MB"); echo byteFormat(1073741824); echo byteFormat(1073741824, "TB", 10); echo byteFormat(1099511627776, "PB", 6); Affiches 4096.00 B 8.00 B 0.00098 KB 1073741824 B 1048576 KB 1024.00 MB 1.00 GB 0.0009765625 TB 0.000977 PB Citer Lien vers le commentaire Partager sur d’autres sites More sharing options...
Messages recommandés
Rejoindre la conversation
Vous pouvez publier maintenant et vous inscrire plus tard. Si vous avez un compte, connectez-vous maintenant pour publier avec votre compte.