在windows下编辑php文件经常会遇到BOM的问题。常见的就是在浏览器里打开网页,审查元素时发现head部分的内容全部跑到body里去了,并且在body开始会有一行空字符串。这是由于记事本等软件会在UTF8格式的文件头部写入BOM,而正是这个东西干扰了php。
这个问题解决方法很简单:
复制这段代码保存为php,放在项目的根目录下,然后运行之,会自动检查BOM并清除。
- <?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._<a href='http://www.chenxuanyi.cn'>http://www.chenxuanyi.cn</a></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);
- }
- ?>
*这段代码不是原创的,不知道从哪里下载来的。