萬盛學電腦網

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

PHP 移除檔案 BOM 標頭完整範例教學

在 PHP 開發中,UTF-8 編碼的檔案若包含 BOM (Byte Order Mark) 會導致輸出異常、Header 已發送錯誤等問題。本文提供一個實用的 PHP 函數,可自動偵測並移除檔案的 BOM 標頭。

什麼是 BOM?

BOM (Byte Order Mark) 是位於 UTF-8 編碼檔案開頭的三個隱藏字元 (EF BB BF),用於標識位元組順序。雖然現代編輯器多已預設不加入 BOM,但跨平台協作或舊專案遷移時仍常遇到此問題。

PHP 移除 BOM 程式碼範例

<?php
function checkBOM($filename) {
    $contents = file_get_contents($filename);
    $charset[1] = substr($contents, 0, 1);
    $charset[2] = substr($contents, 1, 1);
    $charset[3] = substr($contents, 2, 1);

    // 檢查 UTF-8 BOM: EF BB BF
    if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {
        if (isset($GLOBALS['auto']) && $GLOBALS['auto'] == 1) {
            $rest = substr($contents, 3);
            rewrite($filename, $rest);
            return "<font color=red>BOM found, automatically removed.</font>";
        } else {
            return "<font color=red>BOM found.</font>";
        }
    } else {
        return "BOM Not Found.";
    }
}

function rewrite($filename, $data) {
    $filenum = fopen($filename, "w");
    flock($filenum, LOCK_EX);
    fwrite($filenum, $data);
    fclose($filenum);
}

// 使用範例
$auto = 1; // 設為 1 自動移除,0 僅偵測
echo checkBOM("test.php");
?>

進階版:批次掃描目錄移除 BOM

<?php
function removeBOMFromDirectory($dir) {
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS)
    );
    
    foreach ($files as $file) {
        if ($file->isFile() && in_array($file->getExtension(), ['php', 'html', 'css', 'js', 'xml'])) {
            $content = file_get_contents($file->getPathname());
            $bom = pack('H*', 'EFBBBF');
            if (strncmp($content, $bom, 3) === 0) {
                file_put_contents($file->getPathname(), substr($content, 3));
                echo "Removed BOM: " . $file->getPathname() . PHP_EOL;
            }
        }
    }
}

removeBOMFromDirectory(__DIR__ . '/src');
?>

最佳實務建議

  • 編輯器設定儲存為「UTF-8 無 BOM」格式
  • 版本控制加入 `.gitattributes` 規範編碼
  • 部署前加入 CI 檢查腳本自動偵測 BOM
copyright © 萬盛學電腦網 all rights reserved