Preventing form resubmission

FormsHttp

Forms Problem Overview


Page one contains an HTML form. Page two - the code that handles the submitted data.

The form in page one gets submitted. The browser gets redirected to page two. Page two handles the submitted data.

At this point, if page two gets refreshed, a "Confirm Form Resubmission" alert pops up.

Can this be prevented?

Forms Solutions


Solution 1 - Forms

There are 2 approaches people used to take here:

Method 1: Use AJAX + Redirect

This way you post your form in the background using JQuery or something similar to Page2, while the user still sees page1 displayed. Upon successful posting, you redirect the browser to Page2.

Method 2: Post + Redirect to self

This is a common technique on forums. Form on Page1 posts the data to Page2, Page2 processes the data and does what needs to be done, and then it does a HTTP redirect on itself. This way the last "action" the browser remembers is a simple GET on page2, so the form is not being resubmitted upon F5.

Solution 2 - Forms

You need to use PRG - Post/Redirect/Get pattern and you have just implemented the P of PRG. You need to Redirect. (Now days you do not need redirection at all. See this)

PRG is a web development design pattern that prevents some duplicate form submissions which means, Submit form (Post Request 1) -> Redirect -> Get (Request 2)

Under the hood

Redirect status code - HTTP 1.0 with HTTP 302 or HTTP 1.1 with HTTP 303

An HTTP response with redirect status code will additionally provide a URL in the location header field. The user agent (e.g. a web browser) is invited by a response with this code to make a second, otherwise identical, request to the new URL specified in the location field.

The redirect status code is to ensure that in this situation, the web user's browser can safely refresh the server response without causing the initial HTTP POST request to be resubmitted.

Double Submit Problem

Double Submit Problem

Post/Redirect/Get Solution

Post/Redirect/Get Solution

Source

Solution 3 - Forms

Directly, you can't, and that's a good thing. The browser's alert is there for a reason. This thread should answer your question:

https://stackoverflow.com/questions/660329/prevent-back-button-from-showing-post-confirmation-alert

Two key workarounds suggested were the PRG pattern, and an AJAX submit followed by a scripting relocation.

Note that if your method allows for a GET and not a POST submission method, then that would both solve the problem and better fit with convention. Those solutions are provided on the assumption you want/need to POST data.

Solution 4 - Forms

The only way to be 100% sure the same form never gets submitted twice is to embed a unique identifier in each one you issue and track which ones have been submitted at the server. The pitfall there is that if the user backs up to the page where the form was and enters new data, the same form won't work.

Solution 5 - Forms

There are two parts to the answer:

  1. Ensure duplicate posts don't mess with your data on the server side. To do this, embed a unique identifier in the post so that you can reject subsequent requests server side. This pattern is called Idempotent Receiver in messaging terms.

  2. Ensure the user isn't bothered by the possibility of duplicate submits by both

    • redirecting to a GET after the POST (POST redirect GET pattern)
    • disabling the button using javascript

Nothing you do under 2. will totally prevent duplicate submits. People can click very fast and hackers can post anyway. You always need 1. if you want to be absolutely sure there are no duplicates.

Solution 6 - Forms

You can use replaceState method of JQuery:

<script>
   $(document).ready(function(){
   window.history.replaceState('','',window.location.href)
   });
</script>

This is the most elegant way to prevent data again after submission due to post back.

Hope this helps.

Solution 7 - Forms

If you refresh a page with POST data, the browser will confirm your resubmission. If you use GET data, the message will not be displayed. You could also have the second page, after saving the submission, redirect to a third page with no data.

Solution 8 - Forms

Well I found nobody mentioned this trick.

Without redirection, you can still prevent the form confirmation when refresh.

By default, form code is like this:

<form method="post" action="test.php">

now, change it to <form method="post" action="test.php?nonsense=1">

You will see the magic.

I guess its because browsers won't trigger the confirmation alert popup if it gets a GET method (query string) in the url.

Solution 9 - Forms

The PRG pattern can only prevent the resubmission caused by page refreshing. This is not a 100% safe measure.

Usually, I will take actions below to prevent resubmission:

  1. Client Side - Use javascript to prevent duplicate clicks on a button which will trigger form submission. You can just disable the button after the first click.

  2. Server Side - I will calculate a hash on the submitted parameters and save that hash in session or database, so when the duplicated submission was received we can detect the duplication then proper response to the client. However, you can manage to generate a hash at the client side.

In most of the occasions, these measures can help to prevent resubmission.

Solution 10 - Forms

I really like @Angelin's answer. But if you're dealing with some legacy code where this is not practical, this technique might work for you.

At the top of the file

// Protect against resubmits
if (empty($_POST))  {
   $_POST['last_pos_sub'] = time();
} else {
     if (isset($_POST['last_pos_sub'])){
        if ($_POST['last_pos_sub'] == $_SESSION['curr_pos_sub']) {
           redirect back to the file so POST data is not preserved
        }
        $_SESSION['curr_pos_sub'] = $_POST['last_pos_sub'];
     }
}

Then at the end of the form, stick in last_pos_sub as follows:

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

Solution 11 - Forms

Try tris:

function prevent_multi_submit($excl = "validator") {
    $string = "";
    foreach ($_POST as $key => $val) {
	// this test is to exclude a single variable, f.e. a captcha value
	if ($key != $excl) {
	    $string .= $key . $val;
	}
    }
    if (isset($_SESSION['last'])) {
	if ($_SESSION['last'] === md5($string)) {
	    return false;
	} else {
	    $_SESSION['last'] = md5($string);
	    return true;
	}
    } else {
	$_SESSION['last'] = md5($string);
	return true;
    }
}

How to use / example:

if (isset($_POST)) {
    if ($_POST['field'] != "") { // place here the form validation and other controls
	if (prevent_multi_submit()) { // use the function before you call the database or etc
	    mysql_query("INSERT INTO table..."); // or send a mail like...
	    mail($mailto, $sub, $body); // etc
	} else {
	    echo "The form is already processed";
	}
    } else {
	// your error about invalid fields
    }
}

Font: https://www.tutdepot.com/prevent-multiple-form-submission/

Solution 12 - Forms

use js to prevent add data:

if ( window.history.replaceState ) {
    window.history.replaceState( null, null, window.location.href );
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEmanuil RusevView Question on Stackoverflow
Solution 1 - FormsCodeTwiceView Answer on Stackoverflow
Solution 2 - FormsAngelin NadarView Answer on Stackoverflow
Solution 3 - FormsdavinView Answer on Stackoverflow
Solution 4 - FormsBlrflView Answer on Stackoverflow
Solution 5 - FormsiweinView Answer on Stackoverflow
Solution 6 - FormsnoobprogrammerView Answer on Stackoverflow
Solution 7 - FormsJoelView Answer on Stackoverflow
Solution 8 - FormsHighlightView Answer on Stackoverflow
Solution 9 - Formsehe888View Answer on Stackoverflow
Solution 10 - FormsScott C WilsonView Answer on Stackoverflow
Solution 11 - FormsRômulo Z. C. CunhaView Answer on Stackoverflow
Solution 12 - FormsTran Anh HienView Answer on Stackoverflow