3

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.

6
  • Using sessions token is neccessary for other reasons (XSRF) and it solves double submition indirectly. While foolproof and more secure, in some cases more user friendly way is possible with Post-Redirect-Get pattern. Both should be used, but the latter prevents multiple clicks (not sure about older browsers though) and browser's back-forward button resubmittion - so it covers 99% of cases (you could resubmit very slow form only by stopping the request in progress or with wrong ajax request implementation).
    – shudder
    Jan 19, 2017 at 17:48
  • @shudder So if I'm checking for duplicate submissions with a session token, is there a problem if resubmissions occur? Jan 19, 2017 at 19:06
  • Depends what you call a problem. You'll prevent resubmition for sure and you'll need to hadle these cases anyway, but they'll come up much more often, in broad context, and usually with no intentional actions from user. It won't be obvious what your response should be - "Invalid token" (accurate, but you might not care for those who abused app when honest user has no clue what's just happened), "Form already sent" (have I clicked twice or what?), "edit-type form page" (sometimes), "empty form page" (I want to add another one)? Hard to be consistent.
    – shudder
    Jan 19, 2017 at 19:43
  • ^ I mean what advantage does preventing multiple clicks have? Jan 19, 2017 at 19:49
  • Advatage of preventing multiple clicks with session vs. PRG is one: works every time. You need both and they're complementary like input validation and exception handling.
    – shudder
    Jan 19, 2017 at 19:59

3 Answers 3

4

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

13
  • I haven't tried this yet (issues elsewhere on the site); but after the user hits 'submit' and the page reloads, won't the session variable change (line 3) and make them never match? Jan 19, 2017 at 18:01
  • Yes, the idea is to .."to stop duplicate form submissions to my web-page.." as you originally asked for. Meaning the same form can never be submitted twice. I have a feeling you also need to stop displaying the form after the 1st submission is completed (display Thank You message instead etc.) I think you may need to clarify what exactly is happening you are trying to prevent. Are you trying to limit the form submission to 1 per visitor?
    – Milan
    Jan 19, 2017 at 19:17
  • Just edited my question. Let me know if I should provide any other info. Jan 19, 2017 at 19:42
  • So the two "secretFormValues" were different on the first submit; and thus it was returning as a duplicate. Moving $_SESSION['secretFormValue'] = md5(microtime()); to be at the end of your code made it work correctly it seems. Jan 19, 2017 at 21:49
  • yes, there is more than one way how to approach this, also you may want to think about a scenario where someone is using automated script to POST 1000s of submissions against your form page hence the SESSION on top... thx.
    – Milan
    Jan 19, 2017 at 22:10
0

You could simply set a $_SESSION['submittedForm'] = true; variable once the form is submitted by that visitor. You could then check for that session data next time they visit the form page and either not show the form, or throw an error message if they try to submit it again.

0

I suggest an alternative approach. The problem you're trying to solve comes in two variants:

  1. How can I prevent/detect a form from being submitted multiple times (usually accidentally) when the user refreshes the page after submitting?
  2. How can I prevent the submission (or at least make it harder) of form data not coming from an actual form shown on my page?

The solution by Milan solves to both problems, but creates a problem on its own: if the user has the same page open in multiple tabs/windows (remember, they share the same session), this will break.

If you don't care about problem #2, it would be easier to do a "passive" approach, by keeping a list of form IDs in your session data that have already be submitted:

$formID = (isset($_POST["__form_id"]) ? $_POST["__form_id"] : false);
$submittedforms = (isset($_SESSION["submittedforms"]) ? $_SESSION["submittedforms"] : array());

// Check whether this form ID has been submitted before
if (in_array($formID, $submittedforms)) {
    printf("Duplicate submission.");
    exit;
}

// Store the ID of this form submission
$submittedforms[] = $formID;
$_SESSION["submittedforms"] = $submittedforms;

// Continue form processing...

If you need to prevent unauthorized (automated) form submission too, an active approach is needed. I would extend Milan's solution then to store multiple form IDs in your session data (in an array), one for each form generated; and then remove them one-by-one as they are submitted.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.