ThinkPHP 開發中常遇驗證碼頁面輸出亂碼(實為圖片二進制被 BOM 污染)。根因同 Session 失效:UTF-8 BOM 導致標頭輸出提前。提供一個遞歸掃描專案目錄、自動檢測並移除 BOM 的獨立修復腳本,放入專案根目錄訪問即可執行。
remove_bom.php 置於專案根目錄)<?php
if (isset($_GET['dir'])) {
$basedir = $_GET['dir'];
} else {
$basedir = '.';
}
$auto = 1; // 1=自動移除,0=僅檢測
checkdir($basedir);
function checkdir($basedir) {
if ($dh = opendir($basedir)) {
while (($file = readdir($dh)) !== false) {
if ($file != '.' && $file != '..') {
if (!is_dir($basedir . "/" . $file)) {
echo "filename: $basedir/$file " . checkBOM("$basedir/$file") . " <br>";
} else {
$dirname = $basedir . "/" . $file;
checkdir($dirname);
}
}
}
closedir($dh);
}
}
function checkBOM($filename) {
global $auto;
$contents = file_get_contents($filename);
$charset[1] = substr($contents, 0, 1);
$charset[2] = substr($contents, 1, 1);
$charset[3] = substr($contents, 2, 1);
if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {
if ($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>");
}
}
return ("BOM Not Found.");
}
function rewrite($filename, $data) {
$filenum = fopen($filename, "w");
flock($filenum, LOCK_EX);
fwrite($filenum, $data);
fclose($filenum);
}
?>
remove_bom.php 放入專案公開目錄(如 public/ 或根目錄)https://yourdomain/remove_bom.php 掃描當前目錄https://yourdomain/remove_bom.php?dir=./ApplicationBOM found, automatically removed. 表示已修復checkdir 遞歸遍歷目錄樹checkBOM 讀取檔案前 3 位元組,匹配 EF BB BF (UTF-8 BOM)$auto=1 時自動截除前 3 位元組並覆寫檔案(flock 防併發)定期執行掃描腳本 + 統一編輯器配置,徹底杜絕 BOM 導致的驗證碼亂碼、Session 失效等疑難雜症。