[精讚] [會員登入]
1922

[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

你可能感興趣的文章

[PHP7] 讀取mysql資料庫的傳統方法 使用傳統預設的方法來連結mysql資料庫

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

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

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

PHP判斷對方瀏覽器語系 多語系的網頁應該主動偵查瀏覽器的語系,配合使用者跳出合適的語系。

使用Yahoo OAuth2 1/2 使用Yahoo OAuth2來認證我的網站

隨機好文

TFTP Server 安裝及使用 讓設備的網路設定檔或是韌體經由TFTP拷備出來,操作的方法

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

世紀帝國征服者新版本--被遺忘的帝國 世紀帝國征服者新版本--被遺忘的帝國 世紀二代的征服者是精典遊戲中的精典,aofe更好玩...

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

此一時彼一時 我是不是易怒的人,其實我也不知道,總之我常會失控,不知道自己在幹嘛。這近生活過得浮浮的,不是很踏實,總會想太多,我甚至會