用PHP中的表单写入.txt文件

Mah*_*bdi 2 html php forms

我看到了这个问题,我想在评论中提出一个问题,但没有足够的声誉.所以我在这里问这个问题.

我有一个HTML格式的表单:

<form action="myprocessingscript.php" method="POST">
Name : <input name="field1" type="text" />
Email : <input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
Run Code Online (Sandbox Code Playgroud)

和PHP中的处理脚本myprocessingscript.php:

if (isset($_POST['field1']) && isset($_POST['field2'])) {
  $data = 'comments.txt' . $_POST['field1'] . ' ' . $_POST['field2'] . "\n";
  $ret = file_put_contents('comments.txt', $data);

  if ($ret === false) {
    die('There was an error Sending The Comment');
  } 

  else {
    echo "The Comment Has Been Sent Succesfully !";
  }
} 

else {
  die('Fill in The Form Please !');
}

if (isset($_POST['field1']) && isset($_POST['field2'])) {
  $data = 'comments.txt' . $_POST['field1'] . ' ' . $_POST['field2'] . "\n";
  $ret = file_put_contents('comments.txt', $data);

  if ($ret === false) {
    die('There was an error Sending The Comment');
  } 

  else {
    echo "The Comment Has Been Sent Succesfully !";
  }
} 

else {
  die('no post data to process');
}
Run Code Online (Sandbox Code Playgroud)

当我将表单中的内容写入文本文件(comments.txt)时,前一个文本被删除 - 我该怎么办?

CD0*_*001 5

您只需要将'append'标志添加到file_put_contents():

file_put_contents('comments.txt', $data, FILE_APPEND);
Run Code Online (Sandbox Code Playgroud)

请参阅:http://uk3.php.net/manual/en/function.file-put-contents.php