Byte Order Mark (BOM) 是 UTF-8 檔案開頭的三個隱藏位元組 `EF BB BF`,用於告知編輯器檔案編碼。PHP 不會忽略 BOM,會將其視為輸出內容的一部分,導致嚴重副作用。
# Linux/macOS
grep -rl $'\xEF\xBB\xBF' --include="*.php" .
# Windows PowerShell
Get-ChildItem -Recurse -Filter *.php | Where-Object { (Get-Content -Raw -Encoding Byte $_)[0..2] -eq 0xEF,0xBB,0xBF }
<?php
// scan_bom.php
$dir = __DIR__;
$removed = 0;
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($it as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
$content = file_get_contents($file->getPathname());
if (substr($content, 0, 3) === "\xEF\xBB\xBF") {
file_put_contents($file->getPathname(), substr($content, 3));
echo "已移除 BOM: {$file->getPathname()}\n";
$removed++;
}
}
}
echo "完成,共處理 $removed 個檔案。\n";
| 編輯器 | 設定路徑 |
|---|---|
| VS Code | Settings → `files.encoding` = `utf8` (預設不含 BOM) |
| PhpStorm | File → File Encoding → UTF-8 → 取消「Add BOM」 |
| Sublime Text | File → Save with Encoding → UTF-8 (無 BOM) |
| Notepad++ | Encoding → Convert to UTF-8 (非 UTF-8-BOM) |
| Dreamweaver | Modify → Page Properties → Title/Encoding → 取消「Include Unicode Signature (BOM)」 |
在入口檔案 `index.php` 最頂端插入(不推薦長期使用,治標不治本):
<?php
// 必須在任何輸出之前
if (isset($_SERVER['SCRIPT_FILENAME'])) {
$content = file_get_contents($_SERVER['SCRIPT_FILENAME']);
if (substr($content, 0, 3) === "\xEF\xBB\xBF") {
// 僅移除當前腳本 BOM,無法修正 include 的檔案
}
}
原文摘自 cyuyan112233 專欄