UTF-8 BOM (Byte Order Mark) 會在檔案開頭插入 3 個位元組 EF BB BF,導致 PHP 輸出空白字元,進而引發 session_start() 失效、header() 無法送出、Cookie 設定失敗等問題。本文提供完整的批次掃描清理腳本,支援 Web 介面操作與跨平台路徑。
session_start():Headers already sentheader()、setcookie():無法送出標頭<?php
// 設定掃描根目錄(預設為腳本所在目錄)
$HOME = dirname(__FILE__);
// Windows 設為 1,Linux/Mac 設為 0
$WIN = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? 1 : 0;
$BOMBED = [];
RecursiveFolder($HOME);
echo '<h2>已清理下列檔案的 UTF-8 BOM:</h2><p class="found">';
foreach ($BOMBED as $file) {
echo htmlspecialchars($file) . "<br/>\n";
}
echo '</p>';
function RecursiveFolder($path) {
global $BOMBED, $WIN;
$ds = $WIN ? '\\' : '/';
$dir = dir($path);
$subdirs = [];
while (($file = $dir->read()) !== false) {
if ($file === '.' || $file === '..') continue;
$full = $path . $ds . $file;
if (is_dir($full)) {
$subdirs[] = $full;
} else {
$content = file_get_contents($full);
if (SearchBOM($content)) {
$BOMBED[] = $full;
// 移除前 3 位元組並寫回
file_put_contents($full, substr($content, 3));
}
}
}
$dir->close();
foreach ($subdirs as $subdir) {
RecursiveFolder($subdir);
}
}
function SearchBOM($string) {
return substr($string, 0, 3) === pack('CCC', 0xEF, 0xBB, 0xBF);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>UTF-8 BOM 清理工具</title>
<style>
body {font-family: sans-serif; font-size: 14px; line-height: 1.6;}
.found {color: #c00; font-weight: bold;}
</style>
</head>
<body>
<h1>UTF-8 BOM 批次清理完成</h1>
<p>掃描目錄:<code><?php echo htmlspecialchars($HOME); ?></code></p>
<?php if (empty($BOMBED)): ?>
<p style="color: green;">未發現含 BOM 的檔案。</p>
<?php endif; ?>
</body>
</html>
https://yourdomain/bom_cleaner.php。<?php
// cli_bom_clean.php
$root = $argv[1] ?? __DIR__;
$ds = DIRECTORY_SEPARATOR;
$cleaned = 0;
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($iterator as $file) {
if ($file->isFile()) {
$content = file_get_contents($file->getPathname());
if (substr($content, 0, 3) === pack('CCC', 0xEF, 0xBB, 0xBF)) {
file_put_contents($file->getPathname(), substr($content, 3));
echo "Cleaned: {$file->getPathname()}\n";
$cleaned++;
}
}
}
echo "Total cleaned: $cleaned\n";
執行:php cli_bom_clean.php /path/to/project
<?php
// 檢測單一檔案
$file = 'config.php';
$content = file_get_contents($file);
if (substr($content, 0, 3) === pack('CCC', 0xEF, 0xBB, 0xBF)) {
echo "$file 含有 BOM\n";
} else {
echo "$file 正常\n";
}