PHP 수정 구성 파일 샘플 코드

WBOY
풀어 주다: 2016-07-25 08:54:18
원래의
1428명이 탐색했습니다.
  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 = "nn[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<$count; $i ){
  4. $tmp = explode($lines[$i], '=');
  5. if($tmp==null || sizeof($tmp)!=2)
  6. continue;
  7. if(trim($tmp[0])=='$manage["user"]'){
  8. $lines[$i] = $tmp[0]."= ".$manage["user"];
  9. break;
  10. }
  11. }
  12. $str = implode($lines, "rn");
复制代码

然后将$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);

复制代码


원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!