简体   繁体   English

当我刷新网页时,评论被保存在一个文件上两次

[英]comments are being saved twice on a file when i refresh the webpage

i am writing a comment block in my website.我正在我的网站上写一个评论块。 i save the comment in a file and print the contents on the webpage.我将评论保存在文件中并打印网页上的内容。 but the problem is when i refresh the webpage the last comment gets displayed twice.但问题是当我刷新网页时,最后一条评论会显示两次。

Here's my code: i am writing a comment block in my website.这是我的代码:我正在我的网站上写一个评论块。 i save the comment in a file and print the contents on我将评论保存在一个文件中并将内容打印在

the webpage.网页。 but the problem is when i refresh the webpage the last但问题是当我最后刷新网页时

comment gets displayed twice.评论显示两次。

Here's my code:这是我的代码:

<html>


<body>

<form   method="GET">

<textarea rows="15" cols="50" name="comments" >
</textarea>

<input type="submit" value="submit" >

</form>

</body>
</html>



<?php


if(!($_GET["comments"]==null)){
$comments = "Anonymous said:<br>".$_GET

["comments"]."<br><br><br><br>";
$file_comments = fopen("comments.txt","a");
fwrite($file_comments,$comments);
fclose($file_comments);

$_GET["comments"] = null;
$comments = null;

}


$comments = file_get_contents("comments.txt");
echo $comments;


$_GET["comments"] = null;
$comments = null;

?>

Here are quick solutions:以下是快速解决方案:

  1. After your form has been saved or if it has an error, redirect them to the same page but with GET variables in the uri like process.php?action=save .在您的表单被保存或出现错误后,将它们重定向到同一页面,但在 uri 中使用GET变量,如process.php?action=save Use header function for redirection.使用头函数进行重定向。

  2. You also use cookies to save the IP of the person who submits the form and restrict him for certain period to be able to submit the form again.您还使用 cookie 来保存提交表单的人的 IP,并限制他在一段时间内再次提交表单。

The solution is to redirect to the same page.解决方案是重定向到同一页面。 This will work, for example.例如,这将起作用。 Try it.尝试一下。

<html>
<body>
<form method="POST">
  <textarea rows="15" cols="50" name="comments"></textarea>
  <input type="submit" value="submit" name="submit">
</form>
</body>
</html>

<?php
if ( isset( $_POST[ 'submit' ] ) ) {
  $TextArea      = $_POST[ "comments" ];
  $comments      = "Anonymous said:<br>" . $TextArea . "<br><br><br><br>\n\n"; // Add \n\n to write the comments in a different paragraph inside the file.
  $file_comments = file_put_contents( "comments.txt", $comments, FILE_APPEND );
  echo '<script type="text/javascript">window.location ="";</script>';
}
$comments = file_get_contents( "comments.txt" );
echo $comments;
?>

Takes more time to refresh, though.不过需要更多时间来刷新。 The best way to do it is to have the PHP script in another file.最好的方法是将 PHP 脚本放在另一个文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM