Question

I have a multipage form site that I am building.

I am using

$_SESSION['X']=$_POST['X'] 

to store variables from the form into sessions on the page the results are being posted to.

The form is dynamically generated so that the fields are populated with the session variables

$X=$_SESSION['X']

and

(value="$X")

This way when a user clicks back (a button with a page URL, not a history -1) the page is reformed with the values they previously entered.

My problems is that this works fine for one page (i.e. they can go back one page and see values), but 2 pages all values are blank.

Once values are stored in a SESSION shouldn't they stay for the duration of the browser session? They are not being overwritten. Am I misunderstanding session? Any help appreciated.

Code example:

Page 1:

session_start();

//populates fields if session value set for this variable 
$sv_01=$_SESSION['sv_01'];

<<<EOT
<form action="page 2 URL" method="post">
<label> q1 <input value=$sv_01 title="title" type="text" name="sv_01">

<input type="submit" value="Continue" />
</form>
EOT;

Page 2:

session_start();
//stores POST data from page 1 in the session
$_SESSION['sv_01']=$_POST['sv_01']

//populates fields if session value set for this variable 
$sv_02=$_SESSION['sv_02'];

<<<EOT
<form action="page 3 URL" method="post">
<label> q2 <input value=$sv_02 title="title" type="text" name="sv_02">

<input onclick="page 1 URL';" type="button" value="Back" /> <input type="submit" value="Continue" />    
</form>
EOT;

Page 3:

session_start();
//stores POST data from page 2 in the session
$_SESSION['sv_02']=$_POST['sv_02']

//populates fields if session value set for this variable 
$sv_03=$_SESSION['sv_03'];

<<<EOT
<form action="page 4 URL" method="post">
<label> q3 <input value=$sv_03 title="title" type="text" name="sv_03">

<input onclick="page 2 URL';" type="button" value="Back" /> <input type="submit" value="Continue" />    
</form>
EOT;

Moving from page 3 to 2 would be fine - and page 2 to 1 also, but moving from page 3 to 1 would result in page 1 being blank.

Any ideas? Much appreciated

Was it helpful?

Solution

Probably you are overwriting the $_SESSION var with a NULL value that comes from $_POST, because if you are jumping from Page3.php to Page2.php using a link the $_POST content doesn't exist.

So you can solve this verifying if the $_POST value exists before assign its value to $_SESSION. Something like this code:

Page 2.php

if( isset($_POST['sv_01'])
    $_SESSION['sv_01']=$_POST['sv_01'];

Page 3.php

if( isset($_POST['sv_02']) )
    $_SESSION['sv_02']=$_POST['sv_02'];

OTHER TIPS

Maybe try checking that the $_POST members are set first.

Instead of:

$_SESSION['sv_01']=$_POST['sv_01']

Try

if (isset($_POST['sv_01'])) {
  $_SESSION['sv_01']=$_POST['sv_01']
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top