匹配&替换文本文件的某一行

时间:2014-05-16 05:10:36

标签: php html

我正在尝试设置一种方法,用户可以将密码更改为他们也可以访问的网站的某个区域,并且该密码存储为.cfg文本文件的一部分。这是我需要从中提取的文件。该文件的内容如下所示:

[main]
roomname = "Room Name"
topfile = /my/link/here
bannerfile = /my/link/here
bannersfile = /my/link/here
banner_freq = 40
bodyfile = /my/link/here
configfile = /my/link/here
actionfile = /my/link/here
memberfile = /my/link/here
moderatorfile = /my/link/here
logfile = /my/link/here
bootfile = /my/link/here
numusers = 30
password = mypassword
defaultmessage = "$USER$ : $SAYS$"
messagewrapper = '<TABLE WIDTH="100%" border=0 cellpadding=0 cellspacing=0><TR><TD>($DATESTAMP$ : $TIMESTAMP$) $PROVE$ $REGISTERED$ $MOD$ $MESSAGE$</TD></TR></TABLE><P>'

我创建了更改密码表单,但我遇到的问题是处理表单的.php文件。我一直在阅读手册,但不太确定还缺少什么或使用某些变量。

====

修改/更新

我正在使用save.php表单更新下面的代码。它似乎工作,除了它覆盖整个文件空白,我不知道为什么它这样做。我还在发送页面中加入了表单编码。

<?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['password'];
$filevar = '/my/site/location/here/prpwtest/prtest.txt';
$fh = fopen($filevar, "w");
$file_contents = file_get_contents($filevar);
$lines = explode ("\r", $file_contents); // split
for ($i = 0; $i < count($lines); $i++) { // for all lines
if (strpos($lines[$i], 'password = ') === 0)
fwrite($fh, 'password = '.$data.'\r'); // put new password instead of old one
else
fwrite($fh, $lines[$i]); // keep old line
$success_page = '/my/site/location/here/pulldowns/savesuccessful.html';

header('Location: '.$success_page);
}
}

?>

以下是我的保存代码片段:

<form name="loginform" method="post" action="my/site/location/here/prpwtest/prpwtestsave.php">
<input name="password" type="password" /><p><input name="Submit" type="submit" /></form></p></center>
</div>

3 个答案:

答案 0 :(得分:1)

您需要解析$ file_contents中的数据。 即读完这个字符串后,你必须逐行处理它,找到以'password ='开头的字符串来修改它。您可以使用explode()来拆分此字符串:

$lines = explode ("\r", $file_contents); // split
for ($i = 0; $i < count($lines); $i++) { // for all lines
  if (strpos($lines[$i], 'password = ') === 0)
    fwrite($fh, 'password = '.$newpassword.'\r'); // put new password instead of old one
  else
    fwrite($fh, $lines[$i]); // keep old line
}

答案 1 :(得分:1)

尝试一下:

$fileurl = '/path/to/my/file/here/file.cfg';

$replace = 'what I want to put in there when they submit'; 

$file = file($fileurl, FILE_IGNORE_NEW_LINES); // Get file as array of lines

foreach ($file as $n=>$line)
    if (substr($line, 0, 8) === 'password') // Line starts with 'password'
        $file[$n] = 'password = '.$replace; // Replace password line

file_put_contents($fileurl, implode("\n", $file)); // Put file back together

答案 2 :(得分:1)

试试这个。

$array = parse_ini_file('your_ini_file.ini', 'main');
$array['main']['password'] = 'set your password here';

$str = '[main]'."\r\n";
foreach($array['main'] as $key => $value){
 $str .= $key.' = '.$value."\r\n";
}

file_put_contents('test.ini', $str, LOCK_EX);