使用php批量检测文件是否有BOM头并去除BOM头2017-08-22 21:33
我想说“php是世界上最好的语言”,应该不会被打吧?
真的,php真的是非常好的语言。
但是在用php编程的时候,你有没有遇到过这样的问题。
网页之前打开还是好好的,可是今天打开却突然报错?或是头部无缘无故多出一行空白来。
对于这样的问题,小编都不知道遇到过多少次了。
遇到这个问题,经常是因为从服务器上把文件下载下来从而导致的。
罪魁祸首就是UTF-8的BOM头引起的,如果不用相关软件很难发现。
今天小编分享的就是批量检测文件是否有BOM头并去除BOM头的php代码。 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") . "
";
} 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 ('找到包含BOM的文件,已自动删除BOM字符.http://www.santii.com');
} else {
return ('没有找到包含BOM的文件.');
}
} else
return ("BOM Not Found.");
}
function rewrite($filename, $data){
$filenum = fopen($filename, "w");
flock($filenum, LOCK_EX);
fwrite($filenum, $data);
fclose($filenum);
}
将以上代码存为如checkbom.php文件,放到网站根目录下运行即可。
还有个方法就是用EditPlus打开对应的文件,将原有的"UTF8+BOM"格式,另存为"UTF-8"也可以解决BOM头的问题。
使用这个方法的前提是你得知道哪个文件带有BOM头,否则得将所有文件一个一个这样试。