我正在我的网站上写评论栏。 我将评论保存在文件中并在网页上打印内容。 但问题是,当我刷新网页时,最后一条评论会显示两次。
这是我的代码: 我正在我的网站上写评论块。 我将评论保存在文件中并打印内容
网页。 但问题是我最后刷新网页
评论会显示两次。
这是我的代码:
<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;
?>
答案 0 :(得分:2)
以下是快速解决方案:
保存表单或出现错误后,请将其重定向到同一页面,但在GET
等uri中使用process.php?action=save
个变量。使用标题功能进行重定向。
您还使用Cookie来保存提交表单的人的知识产权,并限制他在一段时间内再次提交表单。
答案 1 :(得分:0)
解决方案是重定向到同一页面。例如,这将起作用。试试吧。
<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脚本放在另一个文件中。