PHP修改文本文件中的单行

ant*_*kbd 6 php string text file

我试过并寻找解决方案,但找不到任何明确的解决方案.

基本上,我有一个列出用户名和密码的txt文件.我希望能够更改某个用户的密码.

users.txt文件的内容:

user1,pass1
user2,pass2
user3,pass3
Run Code Online (Sandbox Code Playgroud)

我试过以下php代码:

            // $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);    
Run Code Online (Sandbox Code Playgroud)

Mah*_*hdi 8

这应该有效!:)

$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); 
Run Code Online (Sandbox Code Playgroud)