[精讚] [會員登入]
1904

[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

你可能感興趣的文章

[PHP] preg_match 的貪婪和不貪婪比對 在php preg_match中預設是採用貪婪比對,太貪婪反而不符合需要,因此得採用「非貪婪比對」...

[CodeIgniter 3] COOKIE的使用 PHP CodeIgniter 3 中COOKIE的使用超簡單

[PHP] 字串編碼及解碼函式 為何要將字串編碼?理由很簡單,就是不要讓人家輕易的知道字串內容是什麼。例如點選分頁時,我們常會用這樣的連結: index

[PHP] 將UTF8中文字轉成10進位或16進位數值 原本為了處理 preg_match 中文字的問題[2],用php把中文字轉換成10進位和6進位的數值編碼

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

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

隨機好文

為什麼要買長達二十年的保單? 為什麼要買長達二十年的保單?找一個可以說服我買二十年保單的理由。

[Windows7] 移除IE10及移除IE11 Windows7 不得已的情況要移除IE11或IE10怎麼做?

[札記] 2016.7~12月札記 札記,只是札記

Smarty安裝 smarty 是著名的樣版引擎,非常的好用,用多了突然發現拿掉smarty反而不會寫php了,以下是安裝過程..

[PHP] 檢查IP是否在某個網段內 mtachcidr 要檢查IP是否在某個網段內,要寫幾行?10行?5行? 不用,只要2行。以下是我寫的 code /** * matchCI