dublintech
dublintech

Reputation: 17785

Post Redirect Get - how is POST never ever ever resubmitted?

There are many interesting articles on the Post Redirect Get pattern for example here: http://www.theserverside.com/news/1365146/Redirect-After-Post

But here's a simple question...

If the user does POST and is redirected to a GET. Fine if they hit refresh the browser just sends GET, easy to understand. But if the hit the BACK button after the GET and then hit refresh they can surely hit the POST again? yeah?

I am trying to understand how we can be 100% sure the POST can never be resubmitted?

Upvotes: 1

Views: 730

Answers (2)

Alex
Alex

Reputation: 567

One method for ensuring that a POST is not resubmitted is have a unique identifier associated with that post session, for example, if it's a shopping cart, when they begin checking out, generate a unique ID for that process. Once the checkout has completed (e.g. POST has been sent), remove that ID from the ID's that can be used.

You could also do this by generating a unique key with the form, and if the form is submitted, remove that key from where it is stored.

<input type="hidden" name="key" value="<?php echo generateUniqueKey(); ?>" />

where the generateUniqueKey() function will query a table and insert a unique ID, then return the ID. On the page where you are processing the form, do something like this:

<?php 
    $key = $_POST['key'];
    if (isKeyStillValid ($key)) {
        markKeyAsInvalid ($key);
        // Process form ...
    }
    else {
        die ("You have already submitted this form".);
    }
?>

Where the isKeyStillValid() function will check the database to ensure the key used with the form is still a useable key, and the markKeyAsInvalid() function will remove the key from the database.

Update: Here's an example that I just made which involves exactly what I described earlier. This is a very simple example, and simply uses an auto-incrementing ID in a SQL table as the key, but it should be sufficient as an example. Realistically, you would want something more thought out than this. http://alexloney.com/post/

Upvotes: 1

Oded
Oded

Reputation: 499132

But if the hit the BACK button after the GET and then hit refresh they can surely hit the POST again? yeah?

Yeah.

When the user uses the back button, this can happen - the pattern doesn't protect against that, just against having the result coming up in the same page as the original form, where a refresh (F5) would cause a repost.

how we can be 100% sure the POST can never be resubmitted?

One way is to check the posted values against all values submitted in the last X minutes, discarding duplicates (at the risk of losing intentional duplicates).

Upvotes: 0

Related Questions