萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 批次移除 BOM 標記腳本:遞迴掃描與自動清理

UTF-8 BOM (Byte Order Mark, EF BB BF) 在 PHP 檔案中會導致「headers already sent」錯誤、輸出異常空白、Session/Cookie 設定失效等棘手問題。本文提供一個生產級的遞迴掃描腳本,能自動偵測並移除專案目錄下所有 PHP/HTML/JS/CSS 檔案的 BOM 標記,並支援乾淨模式與實際修改模式雙模操作。

BOM 造成的典型症狀

  • Warning: Cannot modify header information - headers already sent (輸出在 header()/session_start() 之前)
  • 頁面頂端出現不可見的空白行或奇怪字元 
  • XML/JSON 輸出解析失敗 (BOM 破壞格式開頭)
  • 引入檔案時產生多餘換行,破壞版面

完整掃描清理腳本

<?php
/**
 * BOM 批次清理工具
 * 用法:php remove_bom.php [目錄] [--dry-run]
 *   --dry-run : 僅掃描報告,不實際修改 (預設)
 *   --fix     : 實際移除 BOM
 */
declare(strict_types=1);

const BOM_UTF8 = "\xEF\xBB\xBF";

$options = [
    'dir' => __DIR__,
    'dryRun' => true,
    'extensions' => ['php', 'html', 'htm', 'js', 'css', 'xml', 'json', 'txt', 'md', 'vue', 'jsx', 'tsx'],
    'excludeDirs' => ['.git', 'vendor', 'node_modules', 'storage', 'cache', 'logs', '.idea', '.vscode'],
];

// 解析命令列參數
foreach ($argv as $arg) {
    if ($arg === '--fix') $options['dryRun'] = false;
    elseif ($arg === '--dry-run') $options['dryRun'] = true;
    elseif (!in_array($arg, ['--fix', '--dry-run']) && $arg !== $argv[0]) {
        $options['dir'] = realpath($arg) ?: $arg;
    }
}

if (!is_dir($options['dir'])) {
    fwrite(STDERR, "目錄不存在:{$options['dir']}\n");
    exit(1);
}

echo "掃描目錄:{$options['dir']}\n";
echo "模式:" . ($options['dryRun'] ? '乾淨掃描 (不修改)' : '實際修改') . "\n";
echo str_repeat('=', 60) . "\n";

$stats = ['scanned' => 0, 'bomFound' => 0, 'fixed' => 0, 'errors' => 0];

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($options['dir'], RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($iterator as $file) {
    // 跳過排除目錄
    $path = $file->getPathname();
    $relPath = substr($path, strlen($options['dir']) + 1);
    
    foreach ($options['excludeDirs'] as $exDir) {
        if (strpos($relPath, $exDir . DIRECTORY_SEPARATOR) === 0 || 
            strpos($relPath, DIRECTORY_SEPARATOR . $exDir . DIRECTORY_SEPARATOR) !== false) {
            continue 2;
        }
    }
    
    // 副檔名過濾
    $ext = strtolower($file->getExtension());
    if (!in_array($ext, $options['extensions'])) continue;
    
    $stats['scanned']++;
    
    $content = file_get_contents($path);
    if ($content === false) {
        $stats['errors']++;
        echo "[ERROR] 無法讀取:$relPath\n";
        continue;
    }
    
    // 偵測 BOM
    if (str_starts_with($content, BOM_UTF8)) {
        $stats['bomFound']++;
        echo "[BOM] $relPath\n";
        
        if (!$options['dryRun']) {
            $newContent = substr($content, 3);
            // 原子性寫入
            $temp = $path . '.tmp.' . random_bytes(4);
            if (file_put_contents($temp, $newContent) !== false) {
                if (rename($temp, $path)) {
                    $stats['fixed']++;
                    echo "  → 已修復\n";
                } else {
                    $stats['errors']++;
                    @unlink($temp);
                    echo "  → 重命名失敗\n";
                }
            } else {
                $stats['errors']++;
                echo "  → 寫入失敗\n";
            }
        }
    }
}

echo str_repeat('=', 60) . "\n";
echo "掃描完成統計:\n";
echo "  掃描檔案數:{$stats['scanned']}\n";
echo "  發現 BOM:{$stats['bomFound']}\n";
echo "  已修復:{$stats['fixed']}\n";
echo "  錯誤數:{$stats['errors']}\n";

if ($options['dryRun'] && $stats['bomFound'] > 0) {
    echo "\n執行 php {$argv[0]} {$options['dir']} --fix 進行實際修復。\n";
}

腳本特色解析

  1. 遞迴掃描:使用 RecursiveDirectoryIterator + RecursiveIteratorIterator 高效遍歷目錄樹。
  2. 白名單副檔名:避免誤傷二進位檔案 (圖片、字體、編譯產物等)。
  3. 排除目錄:自動跳過 .git, vendor, node_modules 等無需處理目錄。
  4. 原子性寫入:寫入暫存檔再 rename() 覆蓋,防止寫入中斷損壞原檔。
  5. 雙模式操作:預設 --dry-run 安全預覽,確認無誤再執行 --fix。
  6. 詳細統計報告:掃描數、發現數、修復數、錯誤數一目瞭然。

進階:整合到 CI/CD 流程

# .github/workflows/check-bom.yml
name: BOM Check
on: [push, pull_request]
jobs:
  check-bom:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Scan BOM
        run: php scripts/remove_bom.php . --dry-run

IDE/編輯器預防設定

編輯器設定方式
VS Codesettings.json 設定 "files.encoding": "utf8" (預設無 BOM)
PhpStormFile → File Encoding → UTF-8 (取消 "Add BOM")
Sublime TextFile → Save with Encoding → UTF-8 (無 BOM)
Notepad++編碼 → 選擇「UTF-8」而非「UTF-8-BOM」

快速單檔檢查指令

# Linux/macOS: 檢查單一檔案
xxd -l 3 suspect.php | grep -q "ef bb bf" && echo "有 BOM" || echo "無 BOM"

# Windows PowerShell
[System.Text.Encoding]::UTF8.GetPreamble() -eq [System.IO.File]::ReadAllBytes("suspect.php")[0..2]

BOM 問題看似微小,卻能引發難以追蹤的詳細錯誤。建立「無 BOM 編碼」團隊規範、IDE 統一設定、CI 自動檢查,配合本腳本定期清理,徹底根除這類隱性 Bug!

copyright © 萬盛學電腦網 all rights reserved