Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a PHP session to prevent duplicate form submissions?

Tags:

forms

php

session

I want to stop duplicate form submissions to my webpage. Everywhere I look for help, I see use a $_SESSION variable; but I fail to see how sessions and forms could possibly connect to each other outside the context of multiple user accounts.

Can someone show me exactly how this process works?

Edit: I don't want to stop the form being submitted multiple times; only to prevent resubmitting the form with the same values (on page refresh for example).

After the form is processed, the user should see a success/error message and then the form again.

like image 614
Allan Clayton Avatar asked Sep 02 '25 17:09

Allan Clayton


1 Answers

Basically you need to use the unique SESSION value twice. Once somewhere in the form you are trying to submit and once stored in the $_SESSION variable. When the form is POSTED and both values are a match then we have a successful submission, when the form is POSTED but the values are different, no submission occurs.

I.e.:

somewhere on the top of your PHP page:

    <?php
        session_start(); // first line of your PHP page
        $_SESSION['secretFormValue'] = isset($_SESSION["secretFormValue"]) ? $_SESSION["secretFormValue"] : md5(microtime()); // generate some unique session value

       // assign submitted **secretFormValue** from your form to a local variable
        $secretFormValue = isset($_POST["secretFormValue"])? filter_var($_POST["secretFormValue"], FILTER_SANITIZE_STRING) : '';

       // check if the value is present in the **secretFormValue** variable
        if($secretFormValue != '') {

           // check if both values are the same
           if($_SESSION["secretFormValue"] == $secretFormValue) {

                // Process form values & submission ...
                // add your own code...

                unset($_SESSION["secretFormValue"]);

           } else {

               echo "Duplicate submission";
           }

        } else {

           // do some other thing
        }

somewhere below in your form:

<input type="hidden" name="secretFormValue" value"<?php echo $_SESSION['secretFormValue']; ?>">

***I did not test this so please comment in case there is a bug, thx.*

Edit: If you need to prevent submit on page-refresh you may include clearing all the POST values on successful submit so the refresh would fail because of the empty POST i.e.:

unset($_POST); // place it right before unset($_SESSION["secretFormValue"]);

or

Include a redirect to a different page (i.e. Thank You Page) after submission i.e.:

header("Location:ThankYouPage.php"); // place it right after unset($_SESSION["secretFormValue"]);

or just found this one in other SO post:

https://en.wikipedia.org/wiki/Post/Redirect/Get

like image 159
Milan Avatar answered Sep 05 '25 05:09

Milan