Search code examples
phpformsbrowserpostback-button

How do you make the browser re-post form data when using the back button?


I guess my question is in understanding the $_POST handling.

So I have two pages that handle 2 forms. Page 1 asks for some information that will be used in page 2. When submitted the form action uses the same page then redirects to next page upon validation, but only handles the data when $_GET variable ?usersubmit=1.

<form action="<?=$_SERVER['PHP_SELF']?>?usersubmit=1" method="post" name="form1">
<input type="text" name="field1">
</form>

So say I have page called form1.php. Upon submit its sent to form1.php?usersubmit=1. The page now assigns the posted data to session variables and then redirects to form2.php via header('location:form2.php').

<? 
if($_GET['usersubmit']){
    if($_POST['field1']){
      #if valid then assign session variable and redirect to next form
      $_SESSION['field1'] = $_POST['field1'];
      header("location:form2.php");
    }else{
      #if invalid send error message 
      $error = true;
    }
}
?>

My problem is in when users hit the 'back' button on their browser to edit data from a previous form. The browser doesnt re-post this data it just shows them a blank form. I'd prefer not to use $_SESSION data to fill out the forms because I suspect the re-post method may be a quicker and less problematic fix.

I also tried a javascript redirect instead of a header but browsers are smart enough to not send you back to a page that wants to redirect you so it doesnt work.

any help in understanding this would be greatly appreciated. thanks.


Solution

  • The only way to handle it is via a session... HTML5 allows for storing of that kind of data but to be honest I wouldnt even look into it as a possibility just yet, altough it does work.