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服务器实现多session并发运行
Oct 09 PHP
PHP源代码数组统计count分析
Aug 02 PHP
php中将数组存到文件里的实现代码
Jan 19 PHP
让PHP更快的提供文件下载的代码
Jun 13 PHP
探讨:web上存漏洞及原理分析、防范方法
Jun 29 PHP
phpphp图片采集后按原路径保存图片示例
Feb 18 PHP
ThinkPHP文件缓存类代码分享
Apr 22 PHP
WordPress中用于获取文章作者与分类信息的方法整理
Dec 17 PHP
PHP生成及获取JSON文件的方法
Aug 23 PHP
PHP编程文件处理类SplFileObject和SplFileInfo用法实例分析
Jul 22 PHP
PHP标准库(PHP SPL)详解
Mar 16 PHP
PHP7 mongoDB扩展使用的方法分享
May 02 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
单一index.php实现PHP任意层级文件夹遍历(Zjmainstay原创)
2012/07/31 PHP
php在数据库抽象层简单使用PDO的方法
2015/11/03 PHP
phplist及phpmailer(组合使用)通过gmail发送邮件的配置方法
2016/03/30 PHP
PHP.vs.JAVA
2016/04/29 PHP
Thinkphp 框架扩展之类库扩展操作详解
2020/04/23 PHP
getElementById在任意一款浏览器中都可以用吗的疑问回复
2007/05/13 Javascript
js操作二级联动实现代码
2010/07/27 Javascript
jQuery隔行变色与普通JS写法的对比
2013/04/21 Javascript
Javascript实现可旋转的圆圈实例代码
2015/08/04 Javascript
详解vue-cli开发环境跨域问题解决方案
2017/06/06 Javascript
Django使用多数据库的方法
2017/09/06 Javascript
基于bootstrop常用类总结(推荐)
2017/09/11 Javascript
开发Vue树形组件的示例代码
2017/12/21 Javascript
详解vue-cli 快速搭建单页应用之遇到的问题及解决办法
2018/03/01 Javascript
AngularJS模态框模板ngDialog的使用详解
2018/05/11 Javascript
layui弹出层按钮提交iframe表单的方法
2018/08/20 Javascript
用npm安装vue和vue-cli,并使用webpack创建项目的方法
2018/09/28 Javascript
30分钟精通React今年最劲爆的新特性——React Hooks
2019/03/11 Javascript
[59:44]2018DOTA2亚洲邀请赛 3.31 小组赛 B组 paiN vs iG
2018/03/31 DOTA
详解Python多线程
2016/11/14 Python
Python和Java进行DES加密和解密的实例
2018/01/09 Python
Django用户认证系统 组与权限解析
2019/08/02 Python
python cv2在验证码识别中应用实例解析
2019/12/25 Python
Tensorflow中的降维函数tf.reduce_*使用总结
2020/04/20 Python
python opencv实现简易画图板
2020/08/27 Python
从Pytorch模型pth文件中读取参数成numpy矩阵的操作
2021/03/04 Python
使用 css3 transform 属性来变换背景图的方法
2019/05/07 HTML / CSS
电子商务专业毕业生工作推荐信
2013/11/17 职场文书
通信生自我鉴定
2014/01/18 职场文书
优秀团员事迹材料1500字
2014/08/31 职场文书
教师党员学习群众路线心得体会
2014/11/04 职场文书
2015年重阳节活动总结
2015/03/24 职场文书
2015学校六五普法工作总结
2015/04/22 职场文书
2015年村党支部工作总结
2015/04/30 职场文书
隐形的翅膀观后感
2015/06/10 职场文书
JavaScript使用canvas绘制坐标和线
2021/04/28 Javascript