1

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

G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129
Helper123
  • 15
  • 6
  • 2
    After a POST request, to prevent the automatic re-submission of the form data if the page is reloaded it is common to issue a GET request ( using `header` ) – Professor Abronsius Dec 28 '22 at 10:57

1 Answers1

2

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>
G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129