栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

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

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

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;
    }
    
    public function delAllGroup() {
 foreach ($this->domain as $domain) {
     $this->delRecord($domain);
 }
    }
    
    public function addGroup($env) {
 if (! isset($this->ip[$env])) {
     return $this;
 }
 foreach ($this->domain as $domain) {
     $this->addRecord($domain, $this->ip[$env]);
 }
 return $this;
    }
    
    function addRecord($domain, $ip) {
 $this->hosts[$domain] = $ip;
 return $this;
    }
    
    function delRecord($domain) {
 unset($this->hosts[$domain]);
 return $this;
    }
    
    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网络编程技巧总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/40560.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号