PHP实现更改hosts文件的方法示例
本文实例讲述了PHP实现更改hosts文件的方法。分享给大家供大家参考,具体如下:
有这样一个需求,我有多个网址希望在不同的时候对应不同的ip,如果一个个配hosts,这工作显得有些繁琐。写了如下脚本来批量更改。
delAllGroup();
}else{
$hm->addGroup($env);
}
classHostManage{
//hosts文件路径
protected$file;
//hosts记录数组
protected$hosts=array();
//配置文件路径,默认为__FILE__.'.ini';
protected$configFile;
//从ini配置文件读取出来的配置数组
protected$config=array();
//配置文件里面需要配置的域名
protected$domain=array();
//配置文件获取的ip数据
protected$ip=array();
publicfunction__construct($file,$config_file=null){
$this->file=$file;
if($config_file){
$this->configFile=$config_file;
}else{
$this->configFile=__FILE__.'.ini';
}
$this->initHosts()
->initCfg();
}
publicfunction__destruct(){
$this->write();
}
publicfunctioninitHosts(){
$lines=file($this->file);
foreach($linesas$line){
$line=trim($line);
if(empty($line)||$line[0]=='#'){
continue;
}
$item=preg_split('/\s+/',$line);
$this->hosts[$item[1]]=$item[0];
}
return$this;
}
publicfunctioninitCfg(){
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
*/
publicfunctiondelAllGroup(){
foreach($this->domainas$domain){
$this->delRecord($domain);
}
}
/**
*将域配置为指定ip
*@paramtype$env
*@return\HostManage
*/
publicfunctionaddGroup($env){
if(!isset($this->ip[$env])){
return$this;
}
foreach($this->domainas$domain){
$this->addRecord($domain,$this->ip[$env]);
}
return$this;
}
/**
*添加一条host记录
*@paramtype$ip
*@paramtype$domain
*/
functionaddRecord($domain,$ip){
$this->hosts[$domain]=$ip;
return$this;
}
/**
*删除一条host记录
*@paramtype$domain
*/
functiondelRecord($domain){
unset($this->hosts[$domain]);
return$this;
}
/**
*写入host文件
*/
publicfunctionwrite(){
$str='';
foreach($this->hostsas$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
使用方法:
phphosts.phplocal#域名将指向本机127.0.0.1 phphosts.phpdev#域名将指向开发机192.168.1.100 phphosts.php#删除域名的hosts配置
写完后,发现,这明明就是只需要一次查找替换就能完成的工作嘛
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php文件操作总结》、《PHP网络编程技巧总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。