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; } }
复制代码
使用方法: php hosts.php local # 域名将指向本机 127.0.0.1 php hosts.php dev # 域名将指向开发机 192.168.1.100 php hosts.php # 删除域名的 hosts 配置
复制代码
hosts, php
