首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 檔案大小格式化函數大全:從 Bytes 到 YB 的完美轉換

     編輯:PHP 綜合知識

為什麼需要格式化?

資料庫或 filesize() 回傳原始位元組數(如 49957289167),人類難以直觀判斷大小。格式化為 46.53 GB 才具可讀性。

7 種主流實現方式對比

1. 對數運算版(最精簡、支援單位最全)

function setupSize($fileSize) {
    $size = sprintf("%u", $fileSize); // 確保無符號整數
    if ($size == 0) return "0 Bytes";
    $units = [" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB"];
    $i = floor(log($size, 1024));
    return round($size / pow(1024, $i), 2) . $units[$i];
}

特點:數學推導單位索引、支援到 YB (1024^8)、程式碼最短。

2. 迴圈除法版(直觀易懂、經典寫法)

function byte_format($size, $dec = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
    $pos = 0;
    while ($size >= 1024 && $pos < count($units) - 1) {
        $size /= 1024;
        $pos++;
    }
    return round($size, $dec) . ' ' . $units[$pos];
}

特點:邏輯清晰、易維護、可控制小數位。

3. 陣列查表版(法語單位、number_format 格式化)

function format_size($bytes) {
    $units = ['Go' => 1073741824, 'Mo' => 1048576, 'Ko' => 1024, 'octets' => 1];
    foreach ($units as $unit => $threshold) {
        if ($bytes >= $threshold) {
            if ($unit === 'octets') return round($bytes) . ' ' . $unit;
            return number_format($bytes / $threshold, 2, ',', ' ') . ' ' . $unit;
        }
    }
}

特點:法語單位 (Go/Mo/Ko)、使用 number_format 千分位分隔。

4. 結構化回傳版(分離數值與單位,便於進一步處理)

function file_size_format($size = 0, $dec = 2) {
    $units = ["B", "KB", "MB", "GB", "TB", "PB"];
    $pos = 0;
    while ($size >= 1024 && $pos < count($units) - 1) {
        $size /= 1024;
        $pos++;
    }
    return [
        'size' => round($size, $dec),
        'unit' => $units[$pos],
        'formatted' => round($size, $dec) . ' ' . $units[$pos]
    ];
}

// 使用
$info = file_size_format(123456789);
echo $info['formatted']; // 117.74 MB
echo $info['size'];      // 117.74
echo $info['unit'];      // MB

5. Switch 硬編碼版(效能極致、無迴圈開銷)

function fsizeformat($bytes, $prec = 2) {
    $rank = 0;
    $size = $bytes;
    while ($size > 1024) {
        $size /= 1024;
        $rank++;
    }
    $size = round($size, $prec);
    $unit = ['B', 'KB', 'MB', 'GB', 'TB'][$rank] ?? 'PB';
    return $size . ' ' . $unit;
}

6. 檔案路徑直輸入版(整合 filesize、錯誤處理)

function sizeFormat($fileName) {
    $filesize = @filesize($fileName);
    if ($filesize === false) return 'Unknown File';

    if ($filesize >= 1073741824) return round($filesize / 1073741824, 2) . ' GB';
    if ($filesize >= 1048576)    return round($filesize / 1048576, 2) . ' MB';
    if ($filesize >= 1024)       return round($filesize / 1024, 2) . ' KB';
    return $filesize . ' Bytes';
}

7. 區間判斷版(精確控制每個區間的小數位)

function size($byte) {
    if ($byte < 1024)              return $byte . ' B';
    if ($byte < 10240)             return round($byte / 1024, 2) . ' KB';
    if ($byte < 102400)            return round($byte / 1024, 2) . ' KB';
    if ($byte < 1048576)           return round($byte / 1024, 2) . ' KB';
    if ($byte < 10485760)          return round($byte / 1048576, 2) . ' MB';
    if ($byte < 104857600)         return round($byte / 1048576, 2) . ' MB';
    if ($byte < 1073741824)        return round($byte / 1048576, 2) . ' MB';
    return round($byte / 1073741824, 2) . ' GB';
}

特點:針對不同量級給予不同精度(小檔案不顯示小數、大檔案保留兩位)。

效能與選擇建議

版本效能適用場景推薦指數
對數運算版高通用、支援超大單位⭐⭐⭐⭐⭐
迴圈除法版高通用、易維護⭐⭐⭐⭐⭐
結構化回傳版高需分離數值/單位的 API⭐⭐⭐⭐
Switch 版最高極高頻呼叫、熱路徑⭐⭐⭐⭐
區間判斷版中需差異化精度顯示⭐⭐⭐

一鍵整合:推薦的生產級工具函數

/**
 * 檔案大小人性化格式化
 * @param int|string $bytes 位元組數
 * @param int $decimals 小數位數
 * @param bool $si 是否使用 SI 標準 (1000) 而非 IEC (1024)
 * @return string
 */
function human_filesize($bytes, $decimals = 2, $si = false) {
    $bytes = (float) $bytes;
    if ($bytes <= 0) return '0 B';

    $base = $si ? 1000 : 1024;
    $units = $si
        ? ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
        : ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];

    $exp = floor(log($bytes, $base));
    $exp = min($exp, count($units) - 1);
    $value = $bytes / pow($base, $exp);

    return round($value, $decimals) . ' ' . $units[$exp];
}

// 測試
echo human_filesize(49957289167);      // 46.53 GiB (IEC 標準,預設)
echo human_filesize(49957289167, 2, true); // 49.96 GB (SI 標準,硬碟廠商慣用)

此版本同時支援 IEC 標準 (1024,KiB/MiB) 與 SI 標準 (1000,kB/MB),符合國際規範,生產環境強烈推薦。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved