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

问题描述:

I saw this question and I wanted to ask a question in the comment but didn't have enough reputation. So I'm asking the question here.

I have a form in 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">

And a processing script in php, myprocessingscript.php :

if (isset($_POST['field1']) && isset($_POST['field2'])) {
  $data = 'comments.txt' . $_POST['field1'] . ' ' . $_POST['field2'] . "
";
  $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'] . "
";
  $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');
}

When I write something in the form to a text file (comments.txt) the previous text is deleted - what should I do?

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

我有一个HTML表格: p>

 &lt; form action =“myprocessingscript.php  “method =”POST“&gt; 
名称:&lt;输入名称=”field1“type =”text“/&gt; 
电子邮件:&lt;输入名称=”field2“type =”text“/&gt; 
&lt;输入 type =“submit”name =“submit”value =“Save Data”&gt; 
  code>  pre> 
 
 

php中的处理脚本, myprocessingscript.php 代码>: p>

  if(isset($ _ POST ['field1'])&amp;&amp; isset($ _ POST ['field2'])){
 $ data =  'comments.txt'。  $ _POST ['field1']。  ''。  $ _POST ['field2']。  “
”; 
 $ ret = file_put_contents('comments.txt',$ data); 
 
 if if($ ret === false){
 die('发送评论时出错')  ; 
} 
 
其他{
 echo“评论已成功发送!”; 
} 
} 
 
else {
 die('填写表格请!'); 
  } 
 
if(isset($ _ POST ['field1'])&amp;&amp; isset($ _ POST ['field2'])){
 $ data ='comments.txt'。  $ _POST ['field1']。  ''。  $ _POST ['field2']。  “
”; 
 $ ret = file_put_contents('comments.txt',$ data); 
 
 if if($ ret === false){
 die('发送评论时出错')  ; 
} 
 
其他{
 echo“评论已成功发送!”; 
} 
} 
 
else {
 die('没有要处理的帖子数据'); 
}  
  code>  pre> 
 
 

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

You just need to add the 'append' flag to file_put_contents() :

file_put_contents('comments.txt', $data, FILE_APPEND);

See : http://uk3.php.net/manual/en/function.file-put-contents.php