PHP批量去除文件BOM头

auto 是否自动替换 默认否
dir 检查目录 默认./
display 是否显示所有文件 默认只显示有bom头的文件

<?php
empty($_GET['auto']) && $_GET['auto'] = 0;
empty($_GET['dir']) && $_GET['dir'] = './';
empty($_GET['display']) && $_GET['display'] = 0;

$basedir = $_GET['dir'];
$auto = $_GET['auto'];
$display = $_GET['display'];
checkdir($basedir);
/**
 * checkdir
 * @param unknown $basedir
 */
function checkdir($basedir)
{
    global $display;
    if ($dh = opendir($basedir))
    {
        while (($file = readdir($dh)) !== false)
        {
            if ($file != '.' && $file != '..')
            {
                if (! is_dir($basedir . "/" . $file))
                { // 如果是文件
                    $fileName = "filename: {$basedir}/{$file}";
                    $fileName = str_pad($fileName,80,"-");
                    $result = checkBOM("$basedir/$file");
                    if($display==0 && $result =='BOM not found')
                    {
                    }
                    else 
                    {
                        echo $fileName. checkBOM("$basedir/$file") . " <br>";
                    }
                }
                else
                {
                    $dirname = $basedir . "/" . $file; // 如果是目录
                    echo "-----------{$dirname}<br>";
                    checkdir($dirname); // 递归
                }
            }
        }
        closedir($dh);
    }
}
/**
 * check
 * @param unknown $filename
 */
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);
    // BOM
    // 的前三个字符的ASCII
    // 码分别为
    // 239
    // 187
    // 191
    if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191)
    { 
        if ($auto == 1)
        {
            $rest = substr($contents, 3);
            rewrite($filename, $rest);
            return ("<b color=green>BOM found, automatically removed</b>");
        }
        else
        {
            return ("<b color=red>BOM found</b>");
        }
    }
    else
    {
        return ("BOM not found");
    }
}
/**
 * rewrite
 * @param unknown $filename
 * @param unknown $data
 */
function rewrite($filename, $data)
{
    $filenum = fopen($filename, "w");
    flock($filenum, LOCK_EX);
    fwrite($filenum, $data);
    fclose($filenum);
}
上一篇:xtu summer individual 2 E - Double Profiles


下一篇:My97DatePicker-WdatePicker日历日期插件详细示例