BOM是用來判斷文本文件是哪一種Unicode編碼的標記,其本身是一個Unicode字符("\uFEFF"),位于文本文件頭部,BOM本來不影響代碼的解析,但是php除外,PHP會解析BOM,會輸出在頁面里,造成前端有占位發(fā)生布局位移,如果不了解的php BOM 就會對這個平白多出來的東西感到莫名其妙。
我們去掉網站php文件里的BOM信息呢
編輯器可以無保存bom文件,utf-8和utf-8 with bom ,要保存了bom文件 php會報錯 namespace 必須是第一行的代碼,現(xiàn)在是bom信息是第一行,雖然你看不到但是他就是在第一行

我們怎么樣通過代碼的形式批量的去掉文件的bom信息
在網站根目錄下新建一個nobomb.php的文件,文件的代碼為以下內容。主要解決模板多出空的內容、驗證碼不顯示等問題。然后在瀏覽器直接訪問運行nobom.php文件即可。
<?php
if (isset($_GET['dir'])) {
$basedir = $_GET['dir'];
} else {
$basedir = '.';
}
$auto = 1;
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>");
}
} else return ("BOM Not Found.");
}
function rewrite($filename, $data) {
$filenum = fopen($filename, "w");
flock($filenum, LOCK_EX);
fwrite($filenum, $data);
fclose($filenum);
}
運行上面的代碼就可以清除文件的bom信息

上面的截圖看是沒有發(fā)現(xiàn)帶有bom的文件的,有bom的文件 會出現(xiàn)字體加紅色。

去掉后訪問 網站訪問正常
