使用PHP怎么對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 配置
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。