Saving and using session cookies

This is a very common question, and have looked around the web and everything seems to be so complicated and over complicated in its explanation.

I have a form that when its submitted its gets checked to make sure the required fields are filled in, but obviously as nothing there at the mo, when its refreshed all the data is lost, so am applying some session cookies, but I have a very big form.

So the basics I have at the moment are:

session_start();
$_SESSION['contractNumber'] = $_POST['contractNumber'];

This just capturing the 1 input field as below

<form name="form1" action="<?php echo $_SERVER["PHP_SELF"];?>?Admin=Upload New&Contract=0&Number=0" method="post" enctype="multipart/form-data">
if ($ContractU == "1") {
$cNumber=$_GET["Number"];
<input type="text" name="contractNumber" size="10" value="<?php echo $cNumber;?>" /> <img src="images/big-green-tick.gif" height="17" style="position:relative; top:2px;"> 
 } else {
<input type="text" name="contractNumber" size="10" value="<?php echo $cNumber;?>" /> 
 }
</form>

So first off when the page refreshes how does that input field automatically fill itself in with the session cookie, and

In the code that draws your form, you would open the session and check to see whether there is a value in $_SESSION[‘contractNumber’], and if there is, you would output this in the “value” parameter rather than echoing $cNumber. Or assign it to $cNumber, whichever makes more sense.

Hi droopsnoot, do you mean something like this, as it didn’t work

session_start();
$_SESSION['companyName'] = $_POST['companyName'];    

<input type="text" name="companyName" size="60" value="<?php if(isset($_SESSION['companyName']) && !empty($_SESSION['companyName'])) { echo $_SESSION['companyName']; } else { echo $compName; }?>" />

I think I’d split out the php code from the form drawing code to make it look nicer and easier to debug:

<?php
// first, set $compName however you do now, then afterwards:
if (isset($_SESSION['companyName'])) {
  if !(empty($_SESSION['companyName'])) {
    $compName = $_SESSION['companyName'];
    }
  }
?>
<input type="text" name="companyName" size="60" value="<?php echo $compName;?> />

Can you expand on “didn’t work”? Did it display nothing, the wrong value or give an error message? If you var_dump() the session array, what result does it give?

Sorry ye, the value that I tried to save to the session didn’t appear when the page refreshed.

So as a debug step, add at the start of the page code

session_start();
var_dump($_SESSION);

and see what it says. Either it’s not saving properly (your first bit of code in #3 seems OK), or it’s not retrieving properly, or it’s not displaying properly. So the above would show if it can be retrieved, so the next thing would be to put a var_dump($_SESSION); just before you draw the form and see if it’s still there.

Ah yes, that’s helped

[“companyName”]=> NULL

So its not saving to the session in the first place

That won’t help then. Can you show the code that runs to process the POST instruction?

Right, maybe this is where I’m going wrong then, as all I have is what I have shown you really.

This is it all

session_start();
$_SESSION['companyName'] = $_POST['companyName'];
var_dump($_SESSION);

<form name="form1" action="<?php echo $_SERVER["PHP_SELF"];?>?Admin=Upload New&Contract=0&Number=0" method="post" enctype="multipart/form-data">

<input type="text" name="companyName" size="60" value="<?php if(isset($_SESSION['companyName']) && !empty($_SESSION['companyName'])) { echo $_SESSION['companyName']; } else { echo $compName; }?>" /> 

<input type="submit" name="btnsubmit" value="Submit">
</form>

There you go, I got it working now.
I didn’t put the session grab in the right place, and works now.

My only issue now is that the form is huge, so is it ok to do this sort of thing for say 30 odd form values, and they all different too, as some are dropdowns and date pickers

Also I need to clear those sessions as the user can quickly go from this form to another form and then back to start a new contract and wont need the session values

I don’t think it will matter how many values you need to store, as long as you code each appropriately depending on the type of form field type they are.

Normally I’d expect to see something like this structure for processing the form:

<?php
session_start();
if (isset($_POST['Submit'])) { 
  // check all the fields are valid
  ...
  // if they are, do whatever you need to do with the data
  // probably store in db, whatever
  ...
  // if they're not, re-draw the form
  // put the values back in the form so the user doesn't have to type them in again
  // put a comment alongside the field(s) that caused the problem so the user knows what to fix
  }
// code to draw the empty form here, outside of the check for the submit button press, maybe

Now, you might be able to easily combine drawing the empty form (which I’ve done outside the button handling) with re-drawing the form with values shown. I’d probably try to do that, especially if it’s a complex form.

The other thing, though, is that if it’s only for being able to re-draw the form in case the user gets anything wrong, I can’t see any need to be sticking all the form vars into $_SESSION variables only to get them out again. You can just as easily get them from the $_POST array and save all that code. That also saves you having to clear out the $_SESSION array, because you never use it in the first place.

That’s it yes, that’s where I put the session grab and it worked, and good news on the amount of cookies.

On thinking about it, it might be worth keeping the post values in the sessions, and giving the user the option when he returns to the form to clear the sessions, with a little bit of highlighted code to make them aware that the data for contract number is still saved, click here to clear the session data.

So if that was the case, to clear the sessions, do I create a form button called say ‘Clear Session’ and then in the isset function, make each session equal to nothing, as below -

$_SESSION['companyName'] = "";

Thanks for all the help

You can either

unset($_SESSION['sessionvarname']); // to do individual ones
session_destroy(); // to clear all vars

Your way will work, but the variable will still exist which may cause confusion if you have form vars that are legitimately blank.

As for storing the variables for when/if the user comes back, that depends on your application, just think about whether the user is more likely to want to use all new data. If the user has a “usual” value that they select for certain fields, it’s nice to not make them enter it every time but browser auto-completion can deal with that in many cases. If the user usually comes in to create new contracts and the details vary each time, it will be a pain for them to have to press a “clear” button every time, but that depends on the specific usage of the page and isn’t a programming thing. Basically, just because you can store all the details to populate the form doesn’t mean you should.

Yep I got you, makes sense.

Thank you, will crack on with this now and see what brings.

Cheers

Just one more thing, I have lots of drop downs to add to the sessions and the first one I came too I can get the value into the session but it wont read it, could you have a look.

<option <?php if(isset($_SESSION['contractStatus']) && !empty($_SESSION['contractStatus'])) { echo $_SESSION['contractStatus']; } else {  if($cStatus == "Active") echo "selected"; } ?> value="Active">Active</option>

I will take your advice and get the php outside the html, just want to get it working first

I did change it to

<option <?php if(isset($_SESSION['contractStatus']) && !empty($_SESSION['contractStatus'])) { echo "selected"; } else {  if($cStatus == "Active") echo "selected"; } ?> value="Active">Active</option> 

But there three in this drop down and it always selected the last one rather than the right one

It’s a bit hard to say without knowing what the various values are for each of the options, and how that compares to the value of the session variable. What you’re saying there is that if the session variable exists and has something in it (anything at all), then you’ll assume it means the contract is active. What is the code for displaying the other options?

This is the drop down in HTMl

<select name="contractStatus">
<option value="">Select Status</option> 
<option selected value="Active">Active</option> 
<option selected value="On Hold">On Hold</option> 
<option selected value="Terminated">Terminated</option> 
</select>

I selected ‘On Hold’ and that saved to the session as below

["contractStatus"]=> string(7) "On Hold"

So I changed the code to

<select name="contractStatus">
<option value="">Select Status</option> 
<option <?php if(isset($_SESSION['contractStatus']) && !empty($_SESSION['contractStatus'])) { echo "selected"; } else {  if($cStatus == "Active") echo "selected"; } ?> value="Active">Active</option> 
<option <?php if(isset($_SESSION['contractStatus']) && !empty($_SESSION['contractStatus'])) { echo "selected"; } else { if($cStatus == "On Hold") echo "selected"; } ?> value="On Hold">On Hold</option> 
<option <?php if(isset($_SESSION['contractStatus']) && !empty($_SESSION['contractStatus'])) { echo "selected"; } else { if($cStatus == "Terminated") echo "selected"; } ?> value="Terminated">Terminated</option> 
</select>

And it went straight to the Terminated one at the bottom as selected

OK, but you’re only checking to see that the session variable exists, and that it’s not empty, you’re not looking to see what it contains. To make that work you have to look at the value of $_SESSION[‘contractStatus’] in each line, to see if it matches the status you want to make active.

<option <?php if(isset($_SESSION['contractStatus']) && ($_SESSION['contractStatus'] == "Active")) { echo "selected"; } else {  if($cStatus == "Active") echo "selected"; } ?> value="Active">Active</option> 

… and so on for each of the other options and values.

Ah yes, I got you.

Thanks