PHP-BOM

来源:互联网 发布:数据脱敏是什么意思 编辑:程序博客网 时间:2024/06/06 01:15

1.问题描述:所有使用控制层返回的ajax请求都会在前面附加一个小红点,查了一下是因为文件前面有BOM,虽然事后证明并不是所有的文件都带有BOM,但是却造成所有的文件返回数据都出现问题。

2.那么,什么是BOM呢?
答曰:在utf-8编码文件中BOM在文件头部,占用三个字节,用来标示该文件属于utf-8编码,现在已经有很多软件识别bom头,但是还有些不能识别bom头,比如PHP就不能识别bom头,这也是用记事本编辑utf-8编码后执行就会出错的原因了。

3.解决方案,去网上找一些批量处理BOM的脚本运行一下就行了,你也可以运行像editplus、Ultraedit这样的工具来解决。

4.最后提供一个去BOM的文件,运行一下就可以了。

echo '当前查找的目录为:'.$basedir.'当前的设置是:';echo $auto?'检测文件BOM同时去除检测到BOM文件的BOM<br />':'只检测文件BOM不执行去除BOM操作<br />';checkdir($basedir);function checkdir($basedir){    if($dh=opendir($basedir)){        while (($file=readdir($dh)) !== false){            if($file != '.' && $file != '..'){                if(!is_dir($basedir.'/'.$file)){                    echo '文件: '.$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并已自动去除</font>');        }else{            return (' <font color=red>找到BOM</font>');        }    }else{        return (' 没有找到BOM');    }}function rewrite($filename,$data){    $filenum=fopen($filename,'w');    flock($filenum,LOCK_EX);    fwrite($filenum,$data);    fclose($filenum);}?>
原创粉丝点击