前一段时间在公司做一个php的项目,最后将项目安装在客户的个人电脑上的时候很多页面变形了,找了很久都没有发现是什么问题,搞得我很郁闷。第二天用zend studio 打开项目的配置文件时发现在文件的开始的地方出现了一个点点,而且用其他的编辑工具看不到这个点点。我在zend下面把那个点点删了保存后网站就正常了。
后来在网上一查才知道那个点点是utf-8 with bom这种编码格式产生的。php对bom没有进行很好的处理,所以导致了网站运行不正常。而且这种bom在有些IDE里面不容易发现,所以很容易出现问题。我在网上看到一个找bom文件的php脚本,共享出来希望对大家有所帮助。脚本内容如下:
<?php
set_time_limit(0);
class Jo_Dir {
public $__dirs = array();
public function __construct($path) {
if (!is_readable($path)) {
throw new Exception("path not found {$path}");
}
$this->__dirs[0] = $path;
}
protected function _file($file)
{}
protected function _dir($dir)
{}
public function run() {
$i = 0;
while (true) {
if (!isset($this->__dirs[$i])) {
break;
}
$this->_fetch($i);
$i += 1;
}
for ($i = count($this->__dirs) - 1; $i > -1; $i--) {
$this->_dir($this->__dirs[$i]);
}
}
protected function _fetch($i) {
$dh = opendir($this->__dirs[$i]);
$file = null;
while (false !== ($file = readdir($dh))) {
if ($file != '.' && $file != "..") {
$file = $this->__dirs[$i] . '/' . $file;
if (is_dir($file)) {
$this->__dirs[] = $file;
} else {
$this->_file($file);
}
}
}
closedir($dh);
}
}
/**
* 取得文件夹内所有的文件
*/
class My_Dir extends Jo_Dir {
protected function _file($file) {
//echo $file . "<br/>";
$ret = checkBOM("$file");
if(strpos($ret,'BOM found.') && !strpos($file,'.svn'))
{
echo "filename: $file ". $ret ." <br>";
}
}
protected function _dir($dir) {
echo $dir . "<br/>";
}
}
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);
checkBOM ($filename);
return ("<font color=red>BOM found, automatically removed.</font>");
} else {
return ("<font color=red>BOM found.</font>");
}
}
else return ("<font color=blue>BOM Not Found.</font>");
}
function rewrite ($filename, $data) {
$filenum=fopen($filename,"w");
flock($filenum,LOCK_EX);
fwrite($filenum,$data);
fclose($filenum);
}
$dir = new My_Dir(".");
$basedir="."; //修改此行为需要检测的目录,点表示当前目录
$auto=1; //是否自动移除发现的BOM信息。1为是,0为否。
$dir->run();
?>
将上面的脚本保存成1.php,将1.php放入到你要检查的文件夹下面,然后执行这个脚本就可以检查出该文件夹下所有存在bom。