[精讚] [會員登入]
1817

[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

你可能感興趣的文章

[phpmyadmin] 錯誤:您應升級到 MySQL 5.5.0 或更新版本 使用phpmyadmin4出現錯誤:您應升級到 MySQL 5.5.0 或更新版本的解決方式

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

[Smarty5] 如何在樣版中使用php本身的函式 解決 smarty5版後不能直接叫用 php函式的問題

[PHP] UTF8中取出字串中特定的字數 要將字串,例如資料庫取出的TEXT,取出特定的字數

[PHP+ci4] codeignitor4+ smarty5 這篇整合 php 的framework codeignitor4 + smarty5。

PHP 產生連續的日期 要用PHP產生連續的日期,連續月份

我有話要說

>>

限制:留言最高字數1000字。 限制:未登入訪客,每則留言間隔需超過10分鐘,每日最多5則留言。

訪客留言

[無留言]

隨機好文

[MAC] 截取螢幕畫面的方法 截取螢幕畫面的方法,在MAC中叫作螢幕快照,英文是screenshot

[HP DL380G7] 生效啟動第3,4片網卡/開啟或關閉內建的網卡 HP DL380G7 預設第3,4片網卡裝完系統後找不到,難道是壞了?要怎麼辦?

UTF-8的網頁但IE8一片空白 UTF8編碼的網頁在Firefox 正常顯示、但IE8 就是空白,IE8編碼設定是「自動偵測」可是自動偵測到的是 big5...

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

[CodeIgniter 3] 資料庫的使用方法整理2/2 CI3 承襲 CI2,有很多的builder class可以用,依各人的使用習慣,有人喜歡一堆sql字串,有人喜歡用helper