【问题标题】:PHP Modify a single line in a text filePHP 修改文本文件中的单行
【发布时间】:2012-09-11 10:14:36
【问题描述】:

我尝试并寻找解决方案,但找不到任何确定的解决方案。

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

users.txt 文件内容:

user1,pass1
user2,pass2
user3,pass3

我尝试了以下 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);    

【问题讨论】:

  • 您的解决方案的问题是您将文本(顺序)文件作为二进制文件处理。您使用的 fwrite 在这里不起作用。
  • 你的问题是一个例子,说明为什么你不应该使用纯文本文件而是数据库
  • 还有同步的问题。所以,你应该尝试使用flock。或者,它很容易让一些用户发疯。

标签: php string file text


【解决方案1】:

我认为当您获得该文件时,使用 file_get_contents 之后使用 preg_replace 作为特定用户名

我以前做过类似这里的事情

               $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);
        }   

希望这会有所帮助....

【讨论】:

    【解决方案2】:

    这样做的正确方法是使用数据库。数据库可以轻松地进行随机访问,而使用文本文件则更少。

    如果您出于某种原因无法切换到数据库,并且您不希望您的系统有超过一千名用户,那么只需读取整个文件并转换它会简单得多到 PHP 数据结构,进行您需要进行的更改,将其转换回文本并覆盖原始文件。

    在这种情况下,这意味着 file() 将文本文件加载到数组中,每个元素都是用户名和密码作为字符串,以逗号分解数组上的所有元素以分别获取用户名和密码,进行您需要进行的更改,然后将修改后的数据写入光盘。

    您可能还会发现 fgetcsv() 对读取数据很有用。如果您使用 SplFileObject 并且拥有最新版本的 PHP,则 fputcsv() 也可用于将数据写回。

    但是,仅使用数据库是更好的解决方案。适合工作的工具。

    【讨论】:

      【解决方案3】:

      如果你在 *nix 系统上,你可以使用sed;我发现它比玩文件句柄等更整洁:

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

      如果不是,我会同意 GordonM 并将文件解析为 PHP 数据结构,对其进行操作,然后将其放回:

      $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)));
      

      当然,有无数种方法可以做到这一点!

      【讨论】:

        【解决方案4】:

        这应该有效! :)

        $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); 
        

        【讨论】:

          【解决方案5】:
          $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);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-04-04
            • 1970-01-01
            • 2021-05-03
            • 1970-01-01
            • 2012-10-18
            • 2014-06-13
            • 2014-07-03
            相关资源
            最近更新 更多