繁体   English   中英

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

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

我正在我的网站上写一个评论块。 我将评论保存在文件中并打印网页上的内容。 但问题是当我刷新网页时,最后一条评论会显示两次。

这是我的代码:我正在我的网站上写一个评论块。 我将评论保存在一个文件中并将内容打印在

网页。 但问题是当我最后刷新网页时

评论显示两次。

这是我的代码:

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

?>

以下是快速解决方案:

  1. 在您的表单被保存或出现错误后,将它们重定向到同一页面,但在 uri 中使用GET变量,如process.php?action=save 使用头函数进行重定向。

  2. 您还使用 cookie 来保存提交表单的人的 IP,并限制他在一段时间内再次提交表单。

解决方案是重定向到同一页面。 例如,这将起作用。 尝试一下。

<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;
?>

不过需要更多时间来刷新。 最好的方法是将 PHP 脚本放在另一个文件中。

暂无
暂无

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

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