PHP修改文本文件中的一行 [英] PHP Modify a single line in a text file
本文介绍了PHP修改文本文件中的一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图寻找解决方案,但找不到任何确定的答案.
I tried and looked for a solution, but cannot find any definitive.
基本上,我有一个txt文件,其中列出了用户名和密码.我希望能够更改某个用户的密码.
Basically, I have a txt file that lists usernames and passwords. I want to be able to change the password of a certain user.
users.txt文件的内容:
Contents of users.txt file:
user1,pass1
user2,pass2
user3,pass3
我尝试了以下php代码:
I've tried the following php code:
// $username = look for this user (no help required)
// $userpwd = new password to be set
$myFile = "./users.txt";
$fh = fopen($myFile,'r+');
while(!feof($fh)) {
$users = explode(',',fgets($fh));
if ($users[0] == $username) {
$users[1]=$userpwd;
fwrite($fh,"$users[0],$users[1]");
}
}
fclose($fh);
推荐答案
这应该有效! :)
$file = "./users.txt";
$fh = fopen($file,'r+');
// string to put username and passwords
$users = '';
while(!feof($fh)) {
$user = explode(',',fgets($fh));
// take-off old "\r\n"
$username = trim($user[0]);
$password = trim($user[1]);
// check for empty indexes
if (!empty($username) AND !empty($password)) {
if ($username == 'mahdi') {
$password = 'okay';
}
$users .= $username . ',' . $password;
$users .= "\r\n";
}
}
// using file_put_contents() instead of fwrite()
file_put_contents('./users.txt', $users);
fclose($fh);
这篇关于PHP修改文本文件中的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文