PHP实现更改hosts文件的方法示例


Posted in PHP onAugust 08, 2017

本文实例讲述了PHP实现更改hosts文件的方法。分享给大家供大家参考,具体如下:

有这样一个需求,我有多个网址希望在不同的时候对应不同的 ip,如果一个个配 hosts,这工作显得有些繁琐。写了如下脚本来批量更改。

<?php
define('HOST_FILE', 'C:\Windows\System32\drivers\etc\hosts');
$hm = new HostManage(HOST_FILE);
$env = $argv[1];
if (empty($env)) {
    $hm->delAllGroup();
} else {
    $hm->addGroup($env);
}
class HostManage {
    // hosts 文件路径
    protected $file;
    // hosts 记录数组
    protected $hosts = array();
    // 配置文件路径,默认为 __FILE__ . '.ini';
    protected $configFile;
    // 从 ini 配置文件读取出来的配置数组
    protected $config = array();
    // 配置文件里面需要配置的域名
    protected $domain = array();
    // 配置文件获取的 ip 数据
    protected $ip = array();
    public function __construct($file, $config_file = null) {
        $this->file = $file;
        if ($config_file) {
          $this->configFile = $config_file;
        } else {
          $this->configFile = __FILE__ . '.ini';
        }
        $this->initHosts()
            ->initCfg();
    }
    public function __destruct() {
        $this->write();
    }
    public function initHosts() {
        $lines = file($this->file);
        foreach ($lines as $line) {
            $line = trim($line);
            if (empty($line) || $line[0] == '#') {
                continue;
            }
            $item = preg_split('/\s+/', $line);
            $this->hosts[$item[1]] = $item[0];
        }
        return $this;
    }
    public function initCfg() {
        if (! file_exists($this->configFile)) {
            $this->config = array();
        } else {
            $this->config = (parse_ini_file($this->configFile, true));
        }
        $this->domain = array_keys($this->config['domain']);
        $this->ip = $this->config['ip'];
        return $this;
    }
    /**
     * 删除配置文件里域的 hosts
     */
    public function delAllGroup() {
        foreach ($this->domain as $domain) {
            $this->delRecord($domain);
        }
    }
    /**
     * 将域配置为指定 ip
     * @param type $env
     * @return \HostManage
     */
    public function addGroup($env) {
        if (! isset($this->ip[$env])) {
            return $this;
        }
        foreach ($this->domain as $domain) {
            $this->addRecord($domain, $this->ip[$env]);
        }
        return $this;
    }
    /**
     * 添加一条 host 记录
     * @param type $ip
     * @param type $domain
     */
    function addRecord($domain, $ip) {
        $this->hosts[$domain] = $ip;
        return $this;
    }
    /**
     * 删除一条 host 记录
     * @param type $domain
     */
    function delRecord($domain) {
        unset($this->hosts[$domain]);
        return $this;
    }
    /**
     * 写入 host 文件
     */
    public function write() {
        $str = '';
        foreach ($this->hosts as $domain => $ip) {
            $str .= $ip . "\t" . $domain . PHP_EOL;
        }
        file_put_contents($this->file, $str);
        return $this;
    }
}

示例配置文件如下:

# 域名
[domain]
a.example.com=1 # 请无视这个 =1,因为使用了 parse_ini_file 这个函数来解析,如果后面不带值,就获取不到这条记录了
b.example.com=1
c.example.com=1
# ip 记录
[ip]
local=127.0.0.1
dev=192.168.1.100

使用方法:

php hosts.php local # 域名将指向本机 127.0.0.1
php hosts.php dev # 域名将指向开发机 192.168.1.100
php hosts.php # 删除域名的 hosts 配置

写完后,发现,这明明就是只需要一次查找替换就能完成的工作嘛

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
php访问查询mysql数据的三种方法
Oct 09 PHP
php session和cookie使用说明
Apr 07 PHP
php 上传功能实例代码
Apr 13 PHP
php小偷相关截取函数备忘
Nov 28 PHP
php代码运行时间查看类代码分享
Aug 06 PHP
PHP程序漏洞产生的原因分析与防范方法说明
Mar 06 PHP
在Nginx上部署ThinkPHP项目教程
Feb 02 PHP
php短网址和数字之间相互转换的方法
Mar 13 PHP
php禁用cookie后session设置方法分析
Oct 19 PHP
Yii框架参数化查询中IN查询只能查询一个的解决方法
May 20 PHP
基于laravel Request的所有方法详解
Sep 29 PHP
为你的 Laravel 验证器加上多验证场景的实现
Apr 07 PHP
PHP编程实现阳历转换为阴历的方法实例
Aug 08 #PHP
PHP数据分析引擎计算余弦相似度算法示例
Aug 08 #PHP
Eclipse PHPEclipse 配置的具体步骤
Aug 08 #PHP
PHP 文件锁与进程锁的使用示例
Aug 07 #PHP
PHP实现找出有序数组中绝对值最小的数算法分析
Aug 07 #PHP
php基于session锁防止阻塞请求的方法分析
Aug 07 #PHP
在Yii2特定页面如何禁用调试工具栏Debug Toolbar详解
Aug 07 #PHP
You might like
php 获取本机外网/公网IP的代码
2010/05/09 PHP
php数据类型判断函数有哪些
2013/09/23 PHP
ThinkPHP模板自定义标签使用方法
2014/06/26 PHP
php文件操作之小型留言本实例
2015/06/20 PHP
基于JQuery+PHP编写砸金蛋中奖程序
2015/09/08 PHP
Laravel访问出错提示:`Warning: require(/vendor/autoload.php): failed to open stream: No such file or di解决方法
2019/04/02 PHP
php判断/计算闰年的方法小结【三种方法】
2019/07/06 PHP
Windows平台PHP+IECapt实现网页批量截图并创建缩略图功能详解
2019/08/02 PHP
Mozilla中显示textarea中选择的文字
2006/09/07 Javascript
JavaScript Event学习第三章 早期的事件处理程序
2010/02/07 Javascript
javascript页面加载完执行事件代码
2014/02/11 Javascript
使用JSON.parse将json字符串转换成json对象的时候会出错
2014/09/04 Javascript
jquery使用经验小结
2015/05/20 Javascript
jQuery树形控件zTree使用小结
2016/08/02 Javascript
BootStrapTable服务器分页实例解析
2016/12/20 Javascript
js实现多张图片延迟加载效果
2017/07/17 Javascript
基于BootStrap实现简洁注册界面
2017/07/20 Javascript
在小程序中使用canvas的方法示例
2018/09/17 Javascript
Vue v-for中的 input 或 select的值发生改变时触发事件操作
2020/08/31 Javascript
[01:50]WODOTA制作 DOTA2中文宣传片《HERO》
2013/04/28 DOTA
[11:57]《一刀刀一天》第十七期:TI中国军团加油!
2014/05/26 DOTA
Python字符串逐字符或逐词反转方法
2015/05/21 Python
基于Python的XSS测试工具XSStrike使用方法
2017/07/29 Python
使用python判断jpeg图片的完整性实例
2019/06/10 Python
Django中间件拦截未登录url实例详解
2019/09/03 Python
浅析python表达式4+0.5值的数据类型
2020/02/26 Python
Django表单提交后实现获取相同name的不同value值
2020/05/14 Python
python 用struct模块解决黏包问题
2020/11/07 Python
windeln官方海外旗舰店:德淘超人气母婴超市
2017/12/15 全球购物
纪伊国屋新加坡网上书店:Kinokuniya新加坡
2017/12/29 全球购物
Linux的主要特性
2016/09/03 面试题
机关党建工作汇报材料
2014/08/20 职场文书
2014年保密工作总结
2014/11/22 职场文书
家长评语怎么写
2014/12/30 职场文书
Java框架入门之简单介绍SpringBoot框架
2021/06/18 Java/Android
nginx作grpc的反向代理踩坑总结
2021/07/07 Servers