原文链接: http://www.cnblogs.com/Athrun/archive/2010/05/27/1745464.html
另一篇文章:《关于bom.php》,http://hi.baidu.com/aullik5/blog/item/f0e589127a28a2f0f7039e5e.html
另一篇文章:《[BOM]PHP程序的UTF8神秘编码问题之解》,http://www.mlecms.com/tech/56.html
PHP并不会忽略BOM,所以在读取、包含或者引用这些文件时,会把BOM作为该文件开头正文的一部分。根据嵌入式语言的特点,这串字符将被直接执行(显示)出来。由此造成即使页面的 top padding 设置为0,也无法让整个网页紧贴浏览器顶部,因为在html一开头有这3个字符呢!
最大的麻烦还不是这个。受COOKIE送出机制的限制,在这些文件开头已经有BOM的文件中,COOKIE无法送出(因为在COOKIE送出前PHP已经送出了文件头),所以登入和登出功能失效。一切依赖COOKIE、SESSION实现的功能全部无效。
<?php
/*检测并清除BOM*/
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);
}
}
}//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);
}//end function
?>