UTF-8 BOM (Byte Order Mark, EF BB BF) 在 PHP 檔案中會導致「headers already sent」錯誤、輸出異常空白、Session/Cookie 設定失效等棘手問題。本文提供一個生產級的遞迴掃描腳本,能自動偵測並移除專案目錄下所有 PHP/HTML/JS/CSS 檔案的 BOM 標記,並支援乾淨模式與實際修改模式雙模操作。
Warning: Cannot modify header information - headers already sent (輸出在 header()/session_start() 之前)<?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";
}
RecursiveDirectoryIterator + RecursiveIteratorIterator 高效遍歷目錄樹。.git, vendor, node_modules 等無需處理目錄。rename() 覆蓋,防止寫入中斷損壞原檔。--dry-run 安全預覽,確認無誤再執行 --fix。# .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
| 編輯器 | 設定方式 |
|---|---|
| VS Code | settings.json 設定 "files.encoding": "utf8" (預設無 BOM) |
| PhpStorm | File → File Encoding → UTF-8 (取消 "Add BOM") |
| Sublime Text | File → 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!