在 PHP 開發中,UTF-8 編碼的檔案若包含 BOM (Byte Order Mark) 會導致輸出異常、Header 已發送錯誤等問題。本文提供一個實用的 PHP 函數,可自動偵測並移除檔案的 BOM 標頭。
BOM (Byte Order Mark) 是位於 UTF-8 編碼檔案開頭的三個隱藏字元 (EF BB BF),用於標識位元組順序。雖然現代編輯器多已預設不加入 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");
?>
<?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');
?>