批量去除BOM脚本PHP版

今天部署一台新的服务器,部署好后发现验证码不能正确显示。检查了代码,确定没有问题,用Fiddle抓取了验证码的数据,看到有BOM,不知道修改哪个文件的时候带进去了。文件太多,不好查找,于是写了以下脚本,自动查找当前目录下的php文件,如果含有BOM,尝试清除,如果清除失败,会提示,进行手动修改。

PHP代码:<code>

class BomCleaner
{
    private $files = array();
    private $cleaned = array();
    private $uncleaned = array();

    public function clean($base_dir)
    {
        $this->walk_files($base_dir);
        foreach($this->files as $file)
        {
            $state = $this->clean_bom($file);
            if( $state==1 )
                $this->uncleaned[] = $file;
            elseif( $state==2 )
                $this->cleaned[] = $file;
        }
        $this->show_result();
    }

    private function walk_files($dir, $suffix='php')
    {
        foreach( glob($dir.'/*') as $file )
        {
            if( is_dir($file) )
                $this->walk_files($file);
            elseif( is_file($file) && preg_match('/'.$suffix.'$/is', $file) )
                $this->files[] = $file;
        }
    }

    private function clean_bom($file)
    {
        $head = file_get_contents($file, false, null, 0, 3);
        if( bin2hex($head)=='efbbbf' )
        {
            if( !is_writable($file) )
                return 1;

            $data = file_get_contents($file, false, null, 3);
            file_put_contents($file, $data);
            return 2;
        }
        return 0;
    }

    private function show_result()
    {
        if( !$this->cleaned && !$this->uncleaned )
        {
            die('No BOM file found!');
        }
        else
        {
            echo 'Cleaned '.count($this->cleaned).' files: ';
            echo '<ol>';
            foreach($this->cleaned as $file)
                echo '<li>'.$file.'</li>';
            echo '</ol>';

            echo 'Uncleaned '.count($this->uncleaned).' files: (not writeable)';
            echo '<ol>';
            foreach($this->uncleaned as $file)
                echo '<li>'.$file.'</li>';
            echo '</ol>';
        }
    }
}

$cleaner = new BomCleaner;
$cleaner->clean(__DIR__);

</code>

Linux脚本

在linux下,可用以下脚本一键解决,更方便

<code>find . -type f -exec sed -i 's/\xEF\xBB\xBF//' {} ;</code>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,269评论 19 139
  • Composer Repositories Composer源 Firegento - Magento模块Comp...
    零一间阅读 3,973评论 1 66
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,612评论 25 709
  • Php:脚本语言,网站建设,服务器端运行 PHP定义:一种服务器端的HTML脚本/编程语言,是一种简单的、面向对象...
    廖马儿阅读 2,242评论 2 38
  • Ubuntu的发音 Ubuntu,源于非洲祖鲁人和科萨人的语言,发作 oo-boon-too 的音。了解发音是有意...
    萤火虫de梦阅读 99,715评论 9 468