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 相关文章推荐
Banner程序
Oct 09 PHP
php 中的str_replace 函数总结
Apr 27 PHP
PHP下一个非常全面获取图象信息的函数
Nov 20 PHP
ionCube 一款类似zend的PHP加密/解密工具
Jul 25 PHP
apache+php完美解决301重定向的两种方法
Jun 08 PHP
PHP多例模式介绍
Jun 24 PHP
ThinkPHP3.1数据CURD操作快速入门
Jun 19 PHP
yii2.0之GridView自定义按钮和链接用法
Dec 15 PHP
Windows下Apache + PHP SESSION丢失的解决过程全纪录
Apr 07 PHP
php curl 模拟登录并获取数据实例详解
Dec 22 PHP
YII2 实现多语言配置的方法分享
Jan 11 PHP
PHP实现将几张照片拼接到一起的合成图片功能【便于整体打印输出】
Nov 14 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
中国收音机工业发展史
2021/03/02 无线电
php 图片加水印与上传图片加水印php类
2010/05/12 PHP
浅析PHP中Collection 类的设计
2013/06/21 PHP
php-perl哈希算法实现(times33哈希算法)
2013/12/30 PHP
php的sprintf函数的用法 控制浮点数格式
2014/02/14 PHP
Codeigniter实现处理用户登录验证后的URL跳转
2014/06/12 PHP
PHP数据库操作四:mongodb用法分析
2017/08/16 PHP
js活用事件触发对象动作
2008/08/10 Javascript
javascript与CSS复习(三)
2010/06/29 Javascript
javascript高级程序设计第二版第十二章事件要点总结(常用的跨浏览器检测方法)
2012/08/22 Javascript
JS检测图片大小的实例
2013/08/21 Javascript
JS.findElementById()使用介绍
2013/09/21 Javascript
兼容主流浏览器的JS复制内容到剪贴板
2014/12/12 Javascript
jQuery调取jSon数据并展示的方法
2015/01/29 Javascript
jQuery实现360°全景拖动展示
2015/03/18 Javascript
基于JavaScript Array数组方法(新手必看篇)
2016/08/20 Javascript
关于 jQuery Easyui异步加载tree的问题解析
2016/12/06 Javascript
浅谈js中的bind
2019/03/18 Javascript
vue使用recorder.js实现录音功能
2019/11/22 Javascript
vue a标签点击实现赋值方式
2020/09/07 Javascript
深入理解NumPy简明教程---数组2
2016/12/17 Python
Python实现的json文件读取及中文乱码显示问题解决方法
2018/08/06 Python
pygame库实现俄罗斯方块小游戏
2019/10/29 Python
Python+OpenCV实现将图像转换为二进制格式
2020/01/09 Python
python输出第n个默尼森数的实现示例
2020/03/08 Python
python爬虫实现POST request payload形式的请求
2020/04/30 Python
浅谈Python描述数据结构之KMP篇
2020/09/06 Python
Python 中Operator模块的使用
2021/01/30 Python
利用CSS3实现圆角的outline效果的教程
2015/06/05 HTML / CSS
纯HTML5+CSS3制作图片旋转
2016/01/12 HTML / CSS
css3进阶之less实现星空动画的示例代码
2019/09/10 HTML / CSS
SkinCeuticals官网:美国药妆品牌
2018/04/19 全球购物
通用求职信范文模板分享
2013/12/27 职场文书
活动志愿者自荐信
2014/01/27 职场文书
525心理健康活动总结
2015/05/08 职场文书
Nginx虚拟主机的配置步骤过程全解
2022/03/31 Servers