[精讚] [會員登入]
1943

[PHP] 移除檔案的UTF8 BOM

移除檔案的UTF8 BOM

分享此文連結 //n.sfs.tw/11634

分享連結 [PHP] 移除檔案的UTF8 BOM@新精讚
(文章歡迎轉載,務必尊重版權註明連結來源)
2019-10-18 12:47:29 最後編修
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

END

你可能感興趣的文章

設定Google analytics API #1 -- Google網站上的設定 讓你的網站能夠存取你的Google analytics上面的資料

[CodeIgniter 3] 取得controller和method的方法 CodeIgniter 3 取得controller和method的方法

[PHP] IPv6檢查IP是否在某個網段內 mtachcidr6 要檢查IPv6是否在某個IPv6的網段內?

[PHP] 隨機產生一個顏色字串 讓PHP 隨機產生一個顏色字串

PHP 移除陣列中的元素 要移除陣列中的其中一項元素

PHP 數字加解密函式 自寫的數字加解密,勉強用

隨機好文

[jQuery] textarea 的取值和給值 HTML 的 TEXTAREA 標籤若要用 jquery 取值,不能使用 .text() 或 .html() ,使用 .

[AS3] 我做的唯一一個Flash As3遊戲UFO INVADSION [AS3] 我做的唯一一個Flash As3遊戲,是第一個也是最後一個,後來就沒再寫as3,不過as3還滿好玩的。

[CodeIgniter 3] 資料庫的使用方法整理1/2 --Select的使用 [CodeIgniter 3] 資料庫的使用方法整理:Select的使用

[NetBeans] 使用git複製別人的專案 NetBeans使用git複製別人的專案及版本控制

[MAC] 安裝APACHE+PHP OS Darwin OpenIDMac1deAir 15.6.0 Darwin Kernel Version 15.6.