I tried and looked for a solution, but cannot find any definitive.
Basically, I have a txt file that lists usernames and passwords. I want to be able to change the password of a certain user.
Contents of users.txt file:
user1,pass1
user2,pass2
user3,pass3
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);    
                This should works! :)
$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); 
                        I think when you get that file use file_get_contents after that use preg_replace for the particular user name
I have done this in the past some thing like here
               $str = "";
       $reorder_file = FILE_PATH;
       $filecheck = isFileExists($reorder_file);
       if($filecheck != "")
        {
            $reorder_file = $filecheck;
        }
        else
        {
            errorLog("$reorder_file :".FILE_NOT_FOUND);
            $error = true;
            $reorder_file = "";
        }
        if($reorder_file!= "")
        {
            $wishlistbuttonhtml="YOUR PASSWORD WHICH YOU WANT TO REPLACE"
            $somecontent = $wishlistbuttonhtml;
            $Handle = fopen($reorder_file, 'c+');
            $bodytag = file_get_contents($reorder_file);
            $str=$bodytag;
            $pattern = '/(YOUR_REGEX_WILL_GO_HERE_FOR_REPLACING_PWD)/i';
            $replacement = $somecontent;
            $content = preg_replace($pattern, $replacement, $str,-1, $count);
            fwrite($Handle, $content); 
            fclose($Handle);
        }   
Hope this helps....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With