Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Modify a single line in a text file

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);    
like image 845
antikbd Avatar asked Sep 19 '12 05:09

antikbd


2 Answers

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); 
like image 167
Mahdi Avatar answered Nov 17 '22 12:11

Mahdi


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

like image 2
Rajat Modi Avatar answered Nov 17 '22 12:11

Rajat Modi