例如,修改配置文件aaa.conf,内容如下:
 
[username]
kiyone
[password]
123
[class]
chass1
 
要修改[password]下面的123这行密码。
方案采用把这两行替换成空,然后在重新把这两行写在配置文件的结尾。
代码:
 
<?php
$fp = fopen("aaa.conf", 'r');
    $configfile = fread($fp, filesize("aaa.conf"));
    fclose($fp);
    //通过正则替换来做
    $configfile = preg_replace("/n[password](.+?)n/is", "", $configfile);//本只需匹配[password]到下一空行之间的内容,只需写成/[password](.+?)n/is就行了,但是我想把这行前面的空行也去掉,所以在前面加了个n
    //把文件重新写回原来的地方
    $fp = fopen("aaa.conf", 'w');
    fwrite($fp, trim($configfile));
    fclose($fp);
    //在文件最后加入新的password两行
     $newpassword = "456";
    $filename="aaa.conf";//定义操作文件
    $fcontent = file($filename); //file()把整个文件读入一个数组中
    $fp  = fopen("$filename","a");
    $str = "nn[password]n$newpassword";
    fwrite($fp, $str);
//by www.jb200.com
今天做一个php web shell 程序的密码修改,就碰到问题了,密码和程序是在同一个文件里的,如何做到无缝修改,并且不影响程序正常执行。
配置文件的格式类似如下形式:
 
如何提取出 $manage['user'] = ''root''这样的值进行修改工作,因为文件比较大,代码很多,配置文件是在程序的头部分。
基本的思路:
使用file()遍历整个文件,然后找到某个数组的值的字符串是:
$manage["user"]   = "root";
然后,用exploade()来把 $manage["user"] = "";通过"="进行分割,放到两个数组然后把第二个值用更新后的值去替换
最后再把整个字符串重新写入到文件....
但是代码实现起来很困难,上网问高手,给了这么段代码:
 
然后将$str写回到文件
确实,按照我的思路来的话,代码就应该是这样的,但是我去一执行,并不好使。
怎么半呢?想了半天,能不能通过正则表达式来做。
于是又考虑到 $manage[''user'']这样的形式在程序里出现的次数不多,也许能够通过正则替换来修改。
思路:把所有的程序代码读进一个变量里,然后通过正则替换掉这个字符串里的相应内容。
代码:
 
<?php   
// 打开文件
$fp = fopen($manage["file"], 'r');
// 把文件读进$configfile
$configfile = fread($fp, filesize($manage["file"]));
fclose($fp);
// 通过正则替换来做
$configfile = preg_replace("/[$]manage["user"]s*=s*["'].*?["']/is", "$manage["user"] = "$user_name"", $configfile);
$configfile = preg_replace("/[$]manage["pass"]s*=s*["'].*?["']/is", "$manage["pass"] = "$user_pass"", $configfile);
   
// 把文件重新写回原来的地方
$fp = fopen($manage["file"], 'w');
fwrite($fp, trim($configfile));
fclose($fp);