UTF-8 BOM(Byte Order Mark)會導致 PHP 輸出異常、Session 失效、header 已發送等詭異問題。本文提供一個可遞迴掃描目錄、自動檢測並移除 BOM 的完整 PHP 腳本,使用前請務必備份代碼。
EF BB BF(十進位 239, 187, 191). 和 ..<?php
$path = dirname(__FILE__);
scandDir($path);
function bomtoutf8($filename) {
$ef = 239; $bb = 187; $bf = 191;
if (is_dir($filename)) return;
$fd = fopen($filename, "rb");
if (!$fd) exit($filename);
$headers = fread($fd, 3);
fclose($fd);
if (strlen($headers) < 3) return;
if (ord($headers[0]) == $ef && ord($headers[1]) == $bb && ord($headers[2]) == $bf) {
echo $filename, "\n";
$content = file_get_contents($filename);
if (!$content) exit("file get contents failed");
$len = strlen($content);
$content = substr($content, 3);
if ($content === false && $len != 3) exit("substr failed");
elseif ($content === false && $len == 3) $content = "";
$ret = file_put_contents($filename, $content, LOCK_EX);
if ($ret === false) exit("file put contents failed");
echo "successed file $filename\n";
}
}
function scandDir($path) {
$d = dir($path);
if (!$d) exit("dir failed");
while (false !== ($entry = $d->read())) {
if ($entry == '.' || $entry == '..') continue;
$filename = $path . DIRECTORY_SEPARATOR . $entry;
if (is_dir($filename)) {
scandDir($filename);
} else {
bomtoutf8($filename);
}
}
}
?>
remove_bom.php 放入專案根目錄php remove_bom.phpsuccessed 提示vendor/、.git/、storage/ 等目錄一鍵根治 BOM 麻煩,還你乾淨的 UTF-8 編碼環境。