相關(guān)關(guān)鍵詞
關(guān)于我們
最新文章
- PHP中opcode緩存簡(jiǎn)單用法分析
- thinkPHP控制器變量在模板中的顯示方法示例
- PHP move_uploaded_file() 函數(shù)(將上傳的文件移動(dòng)到新位置)
- dirname(__FILE__)的含義和應(yīng)用說(shuō)明
- thinkPHP5框架實(shí)現(xiàn)分頁(yè)查詢功能的方法示例
- PHP中單雙號(hào)與變量
- PHP獲得當(dāng)日零點(diǎn)時(shí)間戳的方法分析
- Laravel ORM對(duì)Model::find方法進(jìn)行緩存示例詳解
- PHP讀寫文件高并發(fā)處理操作實(shí)例詳解
- 【CLI】利用Curl下載文件實(shí)時(shí)進(jìn)度條顯示的實(shí)現(xiàn)
PHP實(shí)現(xiàn)更改hosts文件的方法示例
本文實(shí)例講述了PHP實(shí)現(xiàn)更改hosts文件的方法。分享給大家供大家參考,具體如下:
有這樣一個(gè)需求,我有多個(gè)網(wǎng)址希望在不同的時(shí)候?qū)?yīng)不同的 ip,如果一個(gè)個(gè)配 hosts,這工作顯得有些繁瑣。寫了如下腳本來(lái)批量更改。
<?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 記錄數(shù)組 protected $hosts = array(); // 配置文件路徑,默認(rèn)為 __FILE__ . '.ini'; protected $configFile; // 從 ini 配置文件讀取出來(lái)的配置數(shù)組 protected $config = array(); // 配置文件里面需要配置的域名 protected $domain = array(); // 配置文件獲取的 ip 數(shù)據(jù) 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; } }