萬盛學電腦網

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

PHP 偵測並移除檔案 BOM 標記的完整實作

UTF-8 編碼的檔案若包含 BOM(Byte Order Mark,位元組順序標記),會導致 PHP 輸出時在最前方出現不可見字元,進而干擾 HTTP Header 送出、JSON 格式破壞、XML 解析失效等問題。本文提供完整的偵測與移除程式碼,可整合至專案部署流程中。

BOM 特徵值

UTF-8 BOM 為三個位元組:EF BB BF(十進位 239, 187, 191),位於檔案最開頭。

偵測與移除函式

<?php
/**
 * 檢查並移除檔案開頭的 UTF-8 BOM
 * @param string $filename 檔案路徑
 * @return bool 成功移除回傳 true,無 BOM 或失敗回傳 false
 */
function removeBOM($filename) {
    $contents = file_get_contents($filename);
    if ($contents === false) return false;

    // 檢查前三個位元組
    if (strlen($contents) >= 3 &&
        ord($contents[0]) === 239 &&
        ord($contents[1]) === 187 &&
        ord($contents[2]) === 191) {

        // 移除前三個位元組並覆寫檔案
        $rest = substr($contents, 3);
        return file_put_contents($filename, $rest) !== false;
    }
    return false; // 無 BOM
}

/**
 * 批次處理目錄下所有 PHP 檔案
 */
function cleanDirectoryBOM($dir) {
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
    foreach ($iterator as $file) {
        if ($file->isFile() && $file->getExtension() === 'php') {
            if (removeBOM($file->getPathname())) {
                echo "已移除 BOM: {$file->getPathname()}\n";
            }
        }
    }
}

// 使用範例
// removeBOM('config.php');
// cleanDirectoryBOM(__DIR__ . '/src');

整合建議

  • 部署腳本中加入 cleanDirectoryBOM,確保上線程式碼無 BOM。
  • 編輯器設定儲存為「UTF-8 無 BOM」(VS Code、PhpStorm、Notepad++ 皆支援)。
  • 版本控管(Git)可加入 .gitattributes 強制 eol=lf 與無 BOM。

常見症狀快速自查

症狀可能原因
頁面頂端多出空白行或亂碼包含檔案有 BOM
header() 警告 "Cannot modify header information"BOM 導致輸出提前
json_decode 回傳 null / JSON.parse 失敗BOM 破壞 JSON 格式
XML 解析錯誤 "XML declaration not at start"BOM 佔據檔案開頭

妥善處理 BOM,能避免許多難以追蹤的詭異錯誤,建議納入專案規範與 CI 流程中。

copyright © 萬盛學電腦網 all rights reserved