1. 程式人生 > >PHP批量去除bom頭代碼

PHP批量去除bom頭代碼

amp 去除 opendir add else bom頭 cal fun rest

  最近遇到一個問題編碼問題,有點讓人頭痛,百度的方法好像不太好用,所以我自己也找了很久,現在總結一個小方法去除utf-8bom的方法,頁面總會出現&#65279導致頁面頂部空白一行,方法如下:

  保存為一個php文件,放到網站根目錄下,運行可以遍歷文件夾並自動清除bom,對文件絕對安全,親測過的。

  

<?php
    /*
     * PHP批量去除bom頭代碼的小工具
     */

    if (isset($_GET[‘dir‘])){ //設置文件目錄
        $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")." <br>";
                    }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 ("<font color=red>BOM found, automatically removed.</font>");
            } else {
                return ("<font color=red>BOM found.</font>");
            }
        }
        else return ("BOM Not Found.");
    }

    function rewrite($filename, $data) {
        $filenum = fopen($filename, "w");
        flock($filenum, LOCK_EX);
        fwrite($filenum, $data);
        fclose($filenum);
    }

PHP批量去除bom頭代碼