IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    PHP批量去除bom头代码的小工具

    usity发表于 2016-06-29 04:29:45
    love 0

    在 phpmps 群里有网友抱怨了好几天说本地的验证码一直无法显示,后来听说解决了,问其如何解决的,说是去除了文件 bom 就好了。后来百度到一篇文章也说 thinkphp 的验证码不能显示,某次解决了文件 bom 后竟然好了,于是本篇文章就显得很重要了。

    网上转载的,出处已经不可考了,不知道原作者是谁,在这里先向作者表示感谢。

    代码如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    <?php
        /*
         * PHP批量去除bom头代码的小工具
         * http://blog.kilvn.com/
         */

        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,对文件绝对安全,亲测过的。



沪ICP备19023445号-2号
友情链接