2007年8月10日 星期五

清除UTF-8檔的BOM檔頭

今天不小心用Notepad改了個檔案
結果...BOM檔頭就一直存在...拿不掉...
這個怪怪的Bug害我花了很多時間在測試~~
還好有幸看到石頭閒語的這篇文章...
PHP::關於 PHP 4/5 對 UTF-BOM 的 bug

另外有找到移除的小程式...就節錄下來了~~
原文出處:自動移除文件中的 utf-8 bom的小程式
將此檔案擺在根目錄執行便會自動檢查所有檔案....
並自動修正~


<?php
//remove the utf-8 boms
//by magicbug at gmail dot com
if (isset($_GET[’dir’])){ //config the basedir
$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 found, automatically removed.
");
} else {
return ("BOM found.
");
}
}
else return ("BOM Not Found.
");
}

function rewrite ($filename, $data) {
$filenum = fopen($filename, "w");
flock($filenum, LOCK_EX);
fwrite($filenum, $data);
fclose($filenum);
}
?>

沒有留言: