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的错误信息
Oct 09 PHP
在 PHP 中使用随机数的三个步骤
Oct 09 PHP
PHP 设置MySQL连接字符集的方法
Jan 02 PHP
JSON在PHP中的应用介绍
Sep 08 PHP
PHP的autoload机制的实现解析
Sep 15 PHP
Linux环境下php实现给网站截图的方法
May 03 PHP
PHP使用php-resque库配合Redis实现MQ消息队列的教程
Jun 29 PHP
php添加数据到xml文件的简单例子
Sep 08 PHP
php使用FFmpeg接口获取视频的播放时长、码率、缩略图以及创建时间
Nov 07 PHP
PHP读取文本文件并逐行输出该行使用最多的字符与对应次数的方法
Nov 25 PHP
PHP实现带进度条的Ajax文件上传功能示例
Jul 02 PHP
PHP页面静态化――纯静态与伪静态用法详解
Jun 05 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 和 MySQL 时区的一点总结
2008/03/26 PHP
php用户注册页面利用js进行表单验证具体实例
2013/10/17 PHP
PHP+Ajax+JS实现多图上传
2016/05/07 PHP
URI、URL和URN之间的区别与联系
2006/12/20 Javascript
jQuery中add实现同时选择两个id对象
2010/10/22 Javascript
jQuery Jcrop插件实现图片选取功能
2011/11/23 Javascript
jquery-syntax动态语法着色示例代码
2014/05/14 Javascript
javascript实现动态改变层大小的方法
2015/05/14 Javascript
JS中字符串trim()使用示例
2015/05/26 Javascript
js中substring和substr两者区别和使用方法
2015/11/09 Javascript
倾力总结40条常见的移动端Web页面问题解决方案
2016/05/24 Javascript
jQuery+ajax实现滚动到页面底部自动加载图文列表效果(类似图片懒加载)
2016/06/07 Javascript
利用vue-router实现二级菜单内容转换
2016/11/30 Javascript
Bootstrap modal使用及点击外部不消失的解决方法
2016/12/13 Javascript
Node.js应用设置安全的沙箱环境
2018/04/23 Javascript
vue实现的网易云音乐在线播放和下载功能案例
2019/02/18 Javascript
详解JS浏览器事件循环机制
2019/03/27 Javascript
JS实现音乐导航特效
2020/01/06 Javascript
js页面加载后执行的几种方式小结
2020/01/30 Javascript
为python设置socket代理的方法
2015/01/14 Python
Python中SOAP项目的介绍及其在web开发中的应用
2015/04/14 Python
Python操作列表之List.insert()方法的使用
2015/05/20 Python
Python函数中*args和**kwargs来传递变长参数的用法
2016/01/26 Python
遗传算法python版
2018/03/19 Python
django settings.py 配置文件及介绍
2019/07/15 Python
Python3如何判断三角形的类型
2020/04/12 Python
Python实现敏感词过滤的4种方法
2020/09/12 Python
html5超简单的localStorage实现记住密码的功能实现
2017/09/07 HTML / CSS
德国苹果商店:MacTrade
2020/05/18 全球购物
雪山饭庄的创业计划书范文
2014/01/18 职场文书
中学自我评价
2014/01/31 职场文书
安全大检查实施方案
2014/02/22 职场文书
合作协议书
2014/04/23 职场文书
幼儿园国庆节活动总结
2015/03/23 职场文书
死者家属慰问信
2015/03/24 职场文书
小学数学教学随笔
2015/08/14 职场文书