Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Form Resubmission Reply To: Form Resubmission

#170746
__
Participant

You mean the browser warning? It happens because the browser recognizes that you’re POSTing the same info you already POSTed.

There’s a trick, it’s simple but the idea is little hard to follow:

Say the user submits value=hello to your post.php page. That means the POST and the page will be associated in the browser’s history. (And so when refreshing or backing up, it warns you that you’re submitting the form again: this is what causes the problem.)

The solution is to make sure that, when the user submits the form, the page that it is associated with is never returned: if it is never returned, it won’t be in the browser history, so the user will never be able to refresh/backup to it.

You can do this with a redirect (i.e., Location header).

I’ve found the simplest approach is:

  • when you get a POST (form submission), save the POST data to the session.
  • Do not output (print) anything.
  • send a Location header, redirecting back to the same page.
  • when the session has POST data in it, you know there’s a form submission to be processed.
  • from this point, you can continue processing the form and printing the output as normal.

outline:

<?php
session_start();

if( $_POST ){
    // put form submission in session
    $_SESSION["POST"] = $_POST;
    // redirect and stop script immediately
    header( "Location: http://example.com/this/page.php" );
    exit;
}
if( isset( $_SESSION["POST"] ) ){
    // oooh! a form submission!
    // pretend it was in POST all along
    $_POST = $_SESSION["POST"];
    unset( $_SESSION["POST"] );
}

// continue processing/output as normal