PHP Modify a single line in a text file

后端 未结 5 1958
感情败类
感情败类 2021-01-05 16:00

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 p

相关标签:
5条回答
  • 2021-01-05 16:33

    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); 
    
    0 讨论(0)
  • 2021-01-05 16:33

    If you're on a *nix system you could use sed; I find it neater than playing with file handles etc:

    exec("sed -i '/^$username,.\+\$/$username,$userpwd/g' ./users.txt 2>&1", $output, $return);
    

    If not I'd agree with GordonM and parse the file into a PHP data structure, manipulate it, then put it back:

    $data = file_get_contents('./users.txt');
    
    $users = array_map(function($line) {
      return explode(',', $line);
    }, explode("\n", $data));
    
    foreach ( $users as $i => $user ) {
      if ( $user[0] == $username ) {
        $user[1] = $userpwd;
        $users[$i] = $user;
      }
    }
    
    file_put_contents('./users.txt', implode("\n", array_map(function($line) {
      return implode(',', $line);
    }, $users)));
    

    There are, of course, an infinite number of ways of doing that!

    0 讨论(0)
  • 2021-01-05 16:33
    $fn = fopen("test.txt","r") or die("fail to open file");
    
    $fp = fopen('output.txt', 'w') or die('fail to open output file');
    while($row = fgets($fn)) 
    {
        $num    = explode("++", $row);
    
        $name   = $num[1];
        $sex    = $num[2];
        $blood  =  $num[3];
        $city   = $num[4];
    
        fwrite($fp, "Name:  $name\n");
        fwrite($fp, "Sex:   $sex\n");
        fwrite($fp, "Blood: $blood\n");
        fwrite($fp, "City:  $city\n");
    }
    fclose($fn);
    fclose($fp);
    
    0 讨论(0)
  • 2021-01-05 16:35

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

    0 讨论(0)
  • 2021-01-05 16:37

    The proper way of doing this is to use a database instead. Databases can do random access easily, doing it with text files less so.

    If you can't switch to a database for whatever reason, and you don't expect to have more than about a thousand users for your system, then it would be far simpler to just read the whole file in, convert it to a PHP data structure, make the changes you need to make, convert it back into text and overwrite the original file.

    In this case, that would mean file() to load the text file into an array with each element being a username and password as a string, explode all elements on the array at the comma to get the username and password separately, make the changes you need to make, then write the modified data to disc.

    You might also find fgetcsv() useful for reading the data. If you SplFileObject and have a recent version of PHP then fputcsv() may also be available to write the data back out.

    However, just using a database is a far better solution. Right tool for the job.

    0 讨论(0)
提交回复
热议问题