[精讚] [會員登入]
1884

[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] 好用的php常數 介紹PHP中 __DIR__, __FILE__, __FUNCTION__, __CLASS__, __METHOD__, __LINE__, __NAMESPACE__等常數

[PHP] 如何寫callback function 召回函數(回呼函數) PHP如何寫召回函數或回呼函數(callback function)?

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

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

使用Yahoo OAuth2 2/2 使用Yahoo OAuth2認證我的網頁

[PHP] 將字串的部分加上遮罩的函式 有些資料會想要隱藏部分的字元,例如身分證號或信用卡號、電話等。我寫了一個函式來完成這個功能。

隨機好文

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

[jQuery] select 元件的取值及給值 html中的元件select,在jquery中要如何使用?

[Win7] 燒錄 iso 檔 在Windows7 中內建燒錄程式,可以直接把檔案拉到光碟機裡,再執行燒錄。

讓radio box 或checkbox 好按 在行動裝置下,radio box及checkbox變得很難按得到

關閉瀏覽器表單的自動完成autocomplete 什麼是自動完成?就是當我們在網頁的輸入文字欄位中打入文字時,瀏覽器會把曾輸入過歷史記錄中找出來讓我們選擇。