使用PHP清除文件的BOM
偶尔美工设计师使用Dreamweaver时会加BOM,
这样写PHP程序时会因为BOM头输出产生错误:
如 header() , session_start() 时会提 :
Header may not contain more than a single header, new line detected …
所以上网搜索了一下,知道BOM文件开头的三个字符是0xEF, 0xBB, 0xBF
所以可以使用下边的代码清除BOM.代码如下:
set_time_limit(0); //ignore_user_abort(true); ob_implicit_flush(true); echo '<div style="font-size:12px;">'; findBom(dirname(__FILE__) , true); echo ('<h3>Complete!</h3>'); echo '</div>'; exit; function findBom($path = '.' , $autoRemove = false){ $dir = $path ; $result = opendir($dir); while($filename = readdir($result)){ if($filename == '.' || $filename == '..') continue ; $file = $dir.DIRECTORY_SEPARATOR . $filename ; if(is_dir($file)){ findBom($file , $autoRemove); }elseif(is_file($file) && in_array(strtolower(strrchr($file ,'.')), array('.php','.phtml','html')) ){ $data = file_get_contents($file); if(strlen($data) >= 3){ $charset[1]=substr($data, 0, 1); $charset[2]=substr($data, 1, 1); $charset[3]=substr($data, 2, 1); if (ord($charset[1])==239 && //检测文件开头的字三个符,是否为0xEF, 0xBB, 0xBF ord($charset[2])==187 && ord($charset[3])==191) { if($autoRemove){ $data = substr($data , 3); $fp = @fopen($file , 'wb'); if($fp && flock($fp , LOCK_EX)){ fwrite($fp , $data); echo "<font color=red>$file => Removed</font><br />"; }else{ echo "<font color=red>$file => Found!</font><br />"; } flock($fp , LOCK_UN); fclose($fp); }else{ echo "<font color=red>$file => Found!</font><br />"; } }else{ echo $file .'<br />'; } }else{ echo $file .'<br />'; } } } closedir($result); } |



保存为PHP文件直接运行吗? 我正为此而苦恼,感谢你的教程!
对,建议操作前先备份你的文件