代碼直接記事本打開經常會自動變成含有bom頭格式的文本,當我們知道某個文件含有bom頭的時候我們經常是使用notapad++的encoding -> convert to utf8 讓他刪除bom頭,但是當我們不知道究竟是項目里哪個文件有bom頭的時候,顯然此方法不管用,于是我們可以使用以下的代碼讓他自動檢測并且清除bom頭
<?php
/*檢測并清除BOM*/
$basedir = dirname(__FILE__);//掃描當前文件路徑 可自動設置
$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);
}
}
}//end while
closedir($dh);
}//end if($dh
}//end function
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.");
}//end function
function rewrite($filename, $data){
$filenum = fopen($filename, "w");
flock($filenum, LOCK_EX);
fwrite($filenum, $data);
fclose($filenum);
}