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中使用Oracle数据库(4)
Oct 09 PHP
针对初学PHP者的疑难问答(2)
Oct 09 PHP
header跳转和include包含问题详解
Sep 08 PHP
PHP字符串的连接的简单实例
Dec 30 PHP
php实现检查文章是否被百度收录
Jan 27 PHP
基于ThinkPHP+uploadify+upload+PHPExcel 无刷新导入数据
Sep 23 PHP
CodeIgniter控制器之业务逻辑实例分析
Jan 20 PHP
PHP面试常用算法(推荐)
Jul 22 PHP
PHP实现基于回溯法求解迷宫问题的方法详解
Aug 17 PHP
Laravel框架中Blade模板的用法示例
Aug 30 PHP
基于php中echo用逗号和用点号的区别详解
Jan 23 PHP
laravel5.5添加echarts实现画图功能的方法
Oct 09 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入门
2006/10/09 PHP
php 将字符串按大写字母分隔成字符串数组
2010/04/30 PHP
使用php shell命令合并图片的代码
2011/06/23 PHP
php+javascript实现的动态显示服务器运行程序进度条功能示例
2017/08/07 PHP
Thinkphp5+plupload实现的图片上传功能示例【支持实时预览】
2019/05/08 PHP
浅析PHP echo 和 print 语句
2020/06/30 PHP
jQuery 开发者应该注意的9个错误
2012/05/03 Javascript
谈一谈javascript中继承的多种方式
2016/02/19 Javascript
在js里怎么实现Xcode里的callFuncN方法(详解)
2016/11/05 Javascript
AngularJS定时器的使用与移除操作方法【interval与timeout】
2016/12/14 Javascript
jQuery EasyUI之验证框validatebox实例详解
2017/04/10 jQuery
Vue生命周期示例详解
2017/04/12 Javascript
jQuery 循环遍历改变a标签的href(实例讲解)
2017/07/12 jQuery
webstorm中vue语法的支持详解
2018/05/09 Javascript
让Vue也可以使用Redux的方法
2018/05/23 Javascript
Vue2.X 通过AJAX动态更新数据
2018/07/17 Javascript
node中使用log4js4.x版本记录日志的方法
2019/08/20 Javascript
Python struct模块解析
2014/06/12 Python
Python基本语法经典教程
2016/03/11 Python
Python实现屏幕截图的代码及函数详解
2016/10/01 Python
浅谈Django的缓存机制
2018/08/23 Python
详解python中sort排序使用
2019/03/23 Python
python实现图片横向和纵向拼接
2020/03/05 Python
python else语句在循环中的运用详解
2020/07/06 Python
HTML5新增属性data-*和js/jquery之间的交互及注意事项
2017/08/08 HTML / CSS
Tiqets荷兰:出售欧洲最美丽的景点和博物馆门票
2018/01/09 全球购物
美国唇部护理专家:Sara Happ
2019/06/19 全球购物
英国美术用品购物网站:Cass Art
2019/10/08 全球购物
莫斯科珠宝厂官方网站:Miuz
2020/09/19 全球购物
.net笔试题
2014/03/03 面试题
浪漫婚礼主持词
2014/03/14 职场文书
房产代理公证处委托书
2014/04/04 职场文书
私人房屋买卖协议书
2014/10/04 职场文书
2015年学校总务处工作总结
2015/05/19 职场文书
小学记事作文之200字
2019/08/06 职场文书
python实现三次密码验证的示例
2021/04/29 Python