<?
 
// ****************************
// microsnow
// 此文件用于快速测试UTF8编码的文件是不是加了BOM,并可自动移除
// 基本于 Bob Shen 的版本,二次开发
// ****************************
 
$basedir='WWW_PATH'; //修改此行为需要检测的目录,点表示当前目录
$auto=1; //是否自动移除发现的BOM信息。1为是,0为否。
 
//以下不用改动
read_dir($basedir);
 
// 遍历目录
function read_dir($dir)
{
    static $i = 1;
    static $dir_list = [];
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if ($file == '.' || $file == '..') {
                continue;
            }
            if (is_dir($dir."/".$file)) {
                read_dir($dir."/".$file);
            } else {
                echo "file_name: $dir.$file ".check_bom("$dir/$file")." <br>"; 
            }
        }
        closedir($dh);
    }
}
 
// 检查bom
function check_bom($file_name) {
    global $auto;
    $contents=file_get_contents($file_name);
    $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 ($file_name, $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($file_name, $data) {
    $file_handle =fopen($file_name, "w");
    flock($file_handle, LOCK_EX);
    fwrite($file_handle, $data);
    fclose($file_handle);
}
版权声明:本文为李维亮博主的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:http://www.liweiliang.com/391.html

标签: 快速测试utf8编码的文件是不是加了bom, 并可自动移除

评论已关闭