【问题标题】:Problem new line doesn't create and replace the first line问题新行不创建和替换第一行
【发布时间】:2021-12-19 23:50:28
【问题描述】:
  if(isset($_POST['login_source']))
  { 
    $email = $pass = "";
    // get email id   
    $email = $_POST["email"];
    // get password
    $myfile = fopen("data.txt", "a") or die("Unable to open file!");
    $pass = $_POST["pass"];
    $txt = "$email:$pass\n";
    fwrite($myfile, $txt);
    fclose($myfile);

  }

他没有在 data.txt 中创建新行,而是替换了第一行,我在 localhost 上尝试了这个

【问题讨论】:

标签: php file fopen


【解决方案1】:

问题出在你的file mode usagefopen("data.txt","xxxx"),所以请检查此表,

Mode Description
"r" Opens a file for reading. The file must exist.
"w" Creates an empty file for writing. If a file with the same name already exists, its content is erased and the file is considered as a new empty file.
"a" Appends to a file. Writing operations, append data at the end of the file. The file is created if it does not exist.
"r+" Opens a file to update both reading and writing. The file must exist.
"w+" Creates an empty file for both reading and writing.
"a+" Opens a file for reading and appending.
"rb" Opens a binary file for reading. The file must exist.
"wb" Creates an empty binary file for writing. If the file exists, its contents are cleared unless it is a logical file.
"ab" Opens a binary file in append mode for writing at the end of the file. The fopen function creates the file if it does not exist.
"rb+" Opens a binary file for both reading and writing. The file must exist.
"wb+" Creates an empty binary file for both reading and writing. If the file exists, its contents will be cleared unless it is a logical file.
"ab+" Opens a binary file in append mode for writing at the end of the file. The fopen() function creates the file if it does not exist.

为了解决您的问题,您可以使用附加模式aa+abab+

像这样更改您的代码:

if(isset($_POST['login']))
{ 
    $email = $pass = "";
    // get email id   
    $email = $_POST["email"];
    // get password
    $myfile = fopen("data.txt", "a") or die("Unable to open file!");
    $pass = $_POST["pass"];
    $txt = "$email:$pass\n";
    fwrite($myfile, $txt);
    fclose($myfile);
}

【讨论】:

    【解决方案2】:

    以追加模式打开文件:

    fopen("data.txt", "a")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多