프로그램 개발서

PHP Byte 단위 표시용 함수 본문

PHP

PHP Byte 단위 표시용 함수

rairen 2025. 3. 13. 16:00
if (!function_exists("formatBytes")) {
    // PHP 버전별 최적화된 formatBytes 함수
    function formatBytes($size, $fromUnit = 'B', $toUnit = null, $precision = 2)
    {
        $units = ['B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8];

        $fromUnit = strtoupper($fromUnit);
        $toUnit = $toUnit ? strtoupper($toUnit) : null;

        if (!isset($units[$fromUnit])) {
            throw new Exception("Invalid input unit");
        }

        // Convert input size to bytes
        $bytes = $size * (PHP_VERSION_ID >= 70000 ? (1024 ** $units[$fromUnit]) : pow(1024, $units[$fromUnit]));

        // Determine the target unit
        if ($toUnit) {
            if (!isset($units[$toUnit])) {
                throw new Exception("Invalid output unit");
            }
            $convertedSize = $bytes / (PHP_VERSION_ID >= 70000 ? (1024 ** $units[$toUnit]) : pow(1024, $units[$toUnit]));
            return number_format($convertedSize, $precision) . ' ' . $toUnit;
        }

        // Auto-select appropriate unit
        if (PHP_VERSION_ID >= 70000) {
            $pow = ($bytes > 0) ? floor(log($bytes, 1024)) : 0;
        } else {
            $pow = ($bytes > 0) ? floor(log($bytes) / log(1024)) : 0;
        }

        $pow = min($pow, count($units) - 1);
        $convertedSize = $bytes / (PHP_VERSION_ID >= 70000 ? (1024 ** $pow) : pow(1024, $pow));

        return number_format($convertedSize, $precision) . ' ' . array_search($pow, $units);
    }
}
반응형

'PHP' 카테고리의 다른 글

PHP 5.4.16 버전에서 FCM HTTP V1 푸시 알림 보내는 방법!!  (0) 2024.09.09
[CI4] 카페24에 설치 해보기  (0) 2023.12.30
[phpDocumentor]@todo  (0) 2023.12.06
[phpDocumentor]@version  (0) 2023.12.06
[phpDocumentor]@abstract  (0) 2023.12.06