首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 批次移除 UTF-8 BOM 腳本:遞迴掃描、自動清理與 Web 介面操作

     編輯:PHP 綜合知識

UTF-8 BOM (Byte Order Mark) 會在檔案開頭插入 3 個位元組 EF BB BF,導致 PHP 輸出空白字元,進而引發 session_start() 失效、header() 無法送出、Cookie 設定失敗等問題。本文提供完整的批次掃描清理腳本,支援 Web 介面操作與跨平台路徑。

BOM 造成的問題

  • session_start():Headers already sent
  • header()、setcookie():無法送出標頭
  • XML/JSON 輸出:開頭多出不可見字元,導致解析錯誤
  • 頁面排版:頂端出現不明空白

完整清理腳本(可直接存為 bom_cleaner.php 執行)

<?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>

使用方式

  1. 將腳本放入專案根目錄(或欲掃描的上層目錄)。
  2. 瀏覽器開啟 https://yourdomain/bom_cleaner.php。
  3. 頁面顯示已清理的檔案清單。
  4. 執行前請備份專案! 雖然腳本只移除 BOM,但建議先備份或使用版控系統。

命令列版本(適合 CI/CD 或伺服器無介面環境)

<?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

編輯器設定預防 BOM

  • VS Code: 預設不加 BOM,右下角編碼選單可切換「UTF-8」vs「UTF-8 with BOM」。
  • PhpStorm/IntelliJ: Settings → Editor → File Encodings → 取消「Add BOM for new files」。
  • Notepad++: 編碼選單選「UTF-8」而非「UTF-8-BOM」。
  • Sublime Text: File → Save with Encoding → UTF-8。

快速檢測單一檔案

<?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";
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved