Heim  >  Artikel  >  Backend-Entwicklung  >  php修改配置文件示例代码

php修改配置文件示例代码

WBOY
WBOYOriginal
2016-07-25 08:54:181421Durchsuche
  1. $fp = fopen("aaa.conf", 'r');

  2. $configfile = fread($fp, filesize("aaa.conf"));
  3. fclose($fp);
  4. //通过正则替换来做
  5. $configfile = preg_replace("/\\n\[password\](.+?)\\n/is", "", $configfile);//本只需匹配[password]到下一空行之间的内容,只需写成/\[password\](.+?)\\n/is就行了,但是我想把这行前面的空行也去掉,所以在前面加了个\n
  6. //把文件重新写回原来的地方

  7. $fp = fopen("aaa.conf", 'w');
  8. fwrite($fp, trim($configfile));
  9. fclose($fp);
  10. //在文件最后加入新的password两行
  11. $newpassword = "456";
  12. $filename="aaa.conf";//定义操作文件
  13. $fcontent = file($filename); //file()把整个文件读入一个数组中
  14. $fp = fopen("$filename","a");
  15. $str = "\n\n[password]\n$newpassword";
  16. fwrite($fp, $str);
  17. //by bbs.it-home.org
复制代码

今天做一个php web shell 程序的密码修改,就碰到问题了,密码和程序是在同一个文件里的,如何做到无缝修改,并且不影响程序正常执行。 配置文件的格式类似如下形式:

  1. $lines = file("config.php");
  2. $count =sizeof($lines);
  3. for($i=0; $i $tmp = explode($lines[$i], '=');
  4. if($tmp==null || sizeof($tmp)!=2)
  5. continue;
  6. if(trim($tmp[0])=='$manage["user"]'){
  7. $lines[$i] = $tmp[0]."= ".$manage["user"];
  8. break;
  9. }
  10. }
  11. $str = implode($lines, "\r\n");
复制代码

然后将$str写回到文件

确实,按照我的思路来的话,代码就应该是这样的,但是我去一执行,并不好使。

怎么半呢?想了半天,能不能通过正则表达式来做。 于是又考虑到 $manage[''user'']这样的形式在程序里出现的次数不多,也许能够通过正则替换来修改。

思路:把所有的程序代码读进一个变量里,然后通过正则替换掉这个字符串里的相应内容。

代码:

  1. // 打开文件

  2. $fp = fopen($manage["file"], 'r');
  3. // 把文件读进$configfile

  4. $configfile = fread($fp, filesize($manage["file"]));
  5. fclose($fp);
  6. // 通过正则替换来做

  7. $configfile = preg_replace("/[$]manage\[\"user\"\]\s*\=\s*[\"'].*?[\"']/is", "\$manage[\"user\"] = \"$user_name\"", $configfile);
  8. $configfile = preg_replace("/[$]manage\[\"pass\"\]\s*\=\s*[\"'].*?[\"']/is", "\$manage[\"pass\"] = \"$user_pass\"", $configfile);
  9. // 把文件重新写回原来的地方
  10. $fp = fopen($manage["file"], 'w');
  11. fwrite($fp, trim($configfile));
  12. fclose($fp);
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn