Search code examples
phphtmlforms

the fopen feature keeps on sending me repeated versions of my form that has been posted when I reload the webpage


here is the html/php

<html>

<form method="post" action="<?php echo $_SERVER["PHP_SELF"] ?>">
Enter message<br> <textarea rows="4" cols="40" name="form"></textarea><br>
<input type="submit">
</form>

<?php
$formvalue = $_POST["form"];
if ($formvalue == TRUE) {
$file = fopen("logindetails", "a");
fwrite($file, PHP_EOL);
fwrite($file, $formvalue);
fclose($file);                     
}
else {
    die();
}
?>

</html>

Now whenever I reload the page the previously submitted value or a new line break appears How do I solve this

Please help

I expected the form value from the webpage to be submitted and displayed on a file on the server and with each form submit the file to be updated but instead it repeats the previously sent value onto the file with page refresh or if I haven't filled in anything in the form a blank new line as I added a
attribute to my form


Solution

  • To avoid your POST or GET being send again, you can check & treat them at first in your script, then redirect your script to the same page. Once redirected , if you refresh the page, it will be sent off any POST or GET request.

    Possible update of your code sample:

    <?php
        if(isset($_POST["form"])) {
        $formvalue = $_POST["form"];
        if ($formvalue == TRUE) {
            $file = fopen("logindetails", "a");
            fwrite($file, $formvalue);
            fwrite($file, PHP_EOL);
            fclose($file);  
            header('Location: ' .  $_SERVER['SCRIPT_NAME']);// calls again your page before printing anything
        }
    }
    ?>
    <html>
        <body>
            <form method="post" action="<?php echo $_SERVER["PHP_SELF"] ?>">
            Enter message<br> <textarea rows="4" cols="40" name="form"></textarea><br>
            <input type="submit">
            </form>
        </body>
    </html>