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);
    }
}
반응형