phpformssubmit

Stop PHP from clearing a form


I have 2 questions:


Solution

  • It's not php which clears the form. Php doesn't run in your browser. Your browser posts back the form, which means it discards the page it was displaying and loads whatever the URL the form was posted to returns as the next page.

    Since your form posts back to the same script, if you move the form processing code to the top of the PHP script it will run first before the form is re-rendered.

    You could then set a variable in php which can be used later on to echo the values back into the new copy of the form, if they exist.

    You already have $text declared in the case when the form is submitted, so this is ideal for the purpose. All you need to do additionally is HTML-encode so that echoing it doesn't leave the page open to XSS injection attacks.

    Example:

    <?php
    if(isset($_POST['save']))
    {
        $text = $_POST['sometext'];
        $file = fopen("myfile.txt", "w");
        fwrite($file, $text);
        fclose($file);
    }
    ?>
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>create</title>
    </head>
    <body>
      <form method="post">
        <label for="sometext"></label>
        <input type="sometext" id="sometext" name="sometext" value="<?php echo (isset($text) ? htmlspecialchars($text) : ""); ?>"  />
        <button name="save">Save File</button>
      </form>
    </body>
    </html>