Search code examples
phphtmlcsscomments

How to fix comments from php page got repeatedly posting on page reload?


Hi i am trying to make a comment box for a webiste using only php (without database) almost succeed. But, the comments are repeatedly posting again and again for every page reload. How to fix it ?

My codes in comment.php

<form action="comment.php" method="post">
<label for="name">Name:</label><br/>
<input type="text" name="yourname"><br>
<label for="name">Comment:</label> <br/>
<textarea name="comment" id="comment" cols="30" rows="10"></textarea><br/>
<input type="submit" value="submit">
</form>

<?php
$yourname = $_POST['yourname'];
$comment = $_POST['comment'];
$data = $yourname . "<br>" . $comment . "<br><br>";
$myfile = fopen("comment.txt", "a"); 
fwrite($myfile, $data); 
fclose($myfile);
$myfile = fopen("comment.txt", "r");
echo fread($myfile,filesize("comment.txt"));
?>

Expected Output,

When user enter name and comment and submit, it have to Post a comment. (While reload it should not repeat the last posted comment again)

The output am getting,

When user enter name and comment and submit, it post the comment. But, When reload/refresh that page it post the last comment again. If once again reloaded, again posting the last comment. it repeats for everytime the page reloads.

Kindly help me fix my code. It will be much helpful. Thank You.


Solution

  • You can use PRG Pattern to avoid multiple submissions.

    First of all, check if the request method is POST. If so, save the comment and then redirect back (or any other page you want):

    <?php
    $myfile = fopen('comment.txt', 'a');
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $yourname = $_POST['yourname'];
        $comment = $_POST['comment'];
        $data = $yourname . "<br>" . $comment . "<br><br>"; 
        fwrite($myfile, $data); 
        fclose($myfile);
        header('Location: comment.php');
        die();
    }
    
    $myfile = fopen('comment.txt', 'r');
    echo fread($myfile, filesize('comment.txt'));
    ?>