[PHP] 移除檔案的UTF8 BOM

URL Link //n.sfs.tw/11634

2017-08-16 19:36:01 By 張○○

PHP檔案中若有 unicode bom (utf-8 bom) 的時候,執行時出錯,例如:

demo.php

[前方還有一二個隱藏字元,但你看不見]<?php
session_start();

執行結果

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/pork/public_html/shop/admin/categories.php:1) in home/user/demo.php on line 2

參考 magicbug at gmail dot com 提供的移除程式

remove_utf8bom.php

<?php
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);
}
?>

執行

$ php remove_utf8bom.php

這樣就能把目錄下面的所有utf8 bom檔案都「洗掉』。

延伸閱讀

UTF-8 BOM (Byte Order Mark) 的問題


原文 2009-12-11 16:41:45