PHP Modify a single line in a text file

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....