user1825567
user1825567

Reputation: 153

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;

?>

Upvotes: 1

Views: 234

Answers (2)

Johndave Decano
Johndave Decano

Reputation: 2113

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

Upvotes: 3

Felipe Alameda A
Felipe Alameda A

Reputation: 11809

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.

Upvotes: 1

Related Questions