在 Windows 環境下使用記事本等編輯器將 PHP 文件保存為 UTF-8 格式時,文件頭部會自動添加 3 個字節的 BOM(Byte Order Mark,EF BB BF)。當使用 require/include 載入此類文件時,BOM 會作為輸出內容被發送到瀏覽器,導致:
header()、session_start()、setcookie() 失效(「Headers already sent」錯誤)BOM 旨在標識 UTF-8 字節序,但 PHP 解析器不會自動忽略 它。當文件被 require 載入時,BOM 被視為腳本輸出的一部分,提前發送了 HTTP 體內容,導致後續頭部函數失效。
File → File Encoding → UTF-8,取消「Add BOM」編碼 → 轉為 UTF-8 (無 BOM)File → Save with Encoding → UTF-8文件 → 另存為 → 編碼選 UTF-8(無 BOM)Ctrl+J 打開頁面屬性 → 「標題/編碼」→ 取消勾選「包含 Unicode 簽名 (BOM)」。
<?php
// remove_bom.php - 遞歸清理目錄下所有 PHP 文件的 BOM
$dir = __DIR__;
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($iterator as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
$content = file_get_contents($file->getPathname());
if (substr($content, 0, 3) === "\xEF\xBB\xBF") {
$content = substr($content, 3);
file_put_contents($file->getPathname(), $content);
echo "已清理 BOM: {$file->getPathname()}
";
}
}
}
echo "處理完成";
?>
在入口文件最開頭(<?php 之前無任何字符)添加:
<?php
// 必須是文件的絕對第一行,前面連空行都不能有
if (function_exists('zend_optimizer')) {
// 某些優化器可能干擾
}
ob_start(); // 開啟輸出緩衝,將 BOM 暫存緩衝區
// ... 後續代碼
ob_end_flush(); // 最後輸出
?>
但這只能緩解症狀,**強烈建議從源頭(編輯器保存設置)徹底解決**。
hexdump -C file.php | head -5 查看開頭是否 ef bb bfvar_dump(substr(file_get_contents('file.php'), 0, 3) === "\xEF\xBB\xBF")charset = utf-8、insert_final_newline = true、無 BOMBOM 空行問題是 PHP 開發者從 Windows 遷移到 Linux 部署時的經典坑。「編輯器保存為 UTF-8 無 BOM」是唯一徹底解法。養成良好的編碼習慣,配合自動化檢查,讓「Headers already sent」成為歷史。