[英]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;
?>
以下是快速解決方案:
在您的表單被保存或出現錯誤后,將它們重定向到同一頁面,但在 uri 中使用GET
變量,如process.php?action=save
。 使用頭函數進行重定向。
您還使用 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.