Windows 記事本等編輯器以 UTF-8 with BOM 保存,文件頭部包含 3 字節 `EF BB BF`。
PHP 不識別 BOM,將其作為輸出內容發送瀏覽器,導致:
# Linux 命令檢測
hexdump -C yourfile.php | head -5
# 輸出開頭若見 ef bb bf 即有 BOM
# 或 PHP 檢測
$content = file_get_contents('yourfile.php');
var_dump(bin2hex(substr($content, 0, 3))); // efbbbf 表示有 BOM
| 編輯器 | 操作路徑 |
|---|---|
| EditPlus | 工具 → 首選項 → 文件 → UTF-8 標識 → 總是刪除簽名 |
| UltraEdit | 另存為 → 編碼選擇 "UTF-8 無 BOM" |
| VS Code | 右下角編碼 → "Save with Encoding" → "UTF-8" |
| PhpStorm | File → File Encoding → UTF-8 (無 BOM) |
| Notepad++ | 編碼 → 轉為 UTF-8 (無 BOM) |
# Linux 批量移除 BOM
find . -name "*.php" -exec sed -i '1s/^\xEF\xBB\xBF//' {} \;
# PHP 腳本遞歸清理
function removeBOM($dir) {
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($files as $file) {
if ($file->isFile() && pathinfo($file, PATHINFO_EXTENSION) === 'php') {
$content = file_get_contents($file);
if (substr($content, 0, 3) === "\xEF\xBB\xBF") {
file_put_contents($file, substr($content, 3));
echo "Removed BOM: $file\n";
}
}
}
}
removeBOM(__DIR__);
「無 BOM」應成為 PHP 團隊的肌肉記憶,從源頭杜絕此類部署環境差異 Bug。