scriptygoddess

28 May, 2007

How to use Session Cookies in PHP

Posted by: Jennifer In: PHP

I had written this tutorial sometime ago with the intention of cleaning it up and posting it here. Finally getting around to this. The original purpose of the tutorial was to explain how to use session cookies to a friend of mine who was working on a form that was a number of pages long. I apologize if it seems like I'm starting in the middle of an explanation (I am a bit). The tutorial assumes you've created a few form pages that are connected to each other and that the end result will be taking the data from all the pages and dumping it into a database. This tutorial really focuses on just the session cookie piece and does not go into how to create the forms, or do the inserts for the database.

Since the form spans across a number of pages, the best way to handle this "in between" stage is to store all the values in a session cookie. The reason being, that $_POST array disappears after the first page. Just using the $_POST array, you could spit back all the information to the page – however, in order to submit the data again to be processed and inserted into a database, you'd need to put it into yet another form – specifically hidden values. You can do it this way – there's nothing wrong with it really – it's just more of a pain. By putting all the values into a session cookie, if the user clicked the "back" button to make changes, their info is still remembered, where as with $_POST – it wouldn't be there any more and they'd have to start from scratch! (I know that firefox tends to remember the data – but IE won't)

side note: difference between a session cookie and a regular cookie – session cookies only last as long as your browser is up and running. They will "timeout" after a while too – how long before it times out is a setting in PHP itself (that php.ini file) on the server. Usually it's a few minutes. If it's not long enough – then session cookies probably aren't appropriate for what you need to do! Regular cookies are stored on the users machine. You can set the "lifespan" of this cookie to be several minutes or even several years. So obviously it doesn't go away if the user closes their browser, etc. Since we're only using this information for a moment, we probably wouldn't want the browser to remember it forever and ever – which is why session cookies are perfect.

Ok, so here's how you put all the post values into a session cookie.

First thing – you need to tell the page you're using sessions. Start the session by putting this snippet of code above ANY html tags (including doctype declarations)<?php
session_start();
?>

In this next step we'll want to iterate through that $_POST array and store each piece of information in a similar session cookie array.

To create the session cookies – very easy:<?php
foreach($_POST as $k=>$v) {
$_SESSION['post'][$k]=$v;
}
?>

(I've actually mentioned this method before)

What that says is – for each piece of information we have in the $_POST array – $k will be the index name and $v will be the value – So if you have a field with the name "First_Name" it's value is now stored in this session cookie: $_SESSION['post']['First_Name'].

Another side note – the reason why I'm storing them in a sub-array $_SESSION['post']['FIELDNAME'] as opposed to just $_SESSION['FIELDNAME'] is in the event that the field name overlaps with something else that might be used. In fact, you can rename 'post' to be specific to the form you're working on to ensure it's not overlapping with anything else… ie. $_SESSION['myContactForm']['FIELDNAME']

Ok – once you do all the above (start the session – get all the data into a session cookie, etc.) you can then display each piece by using the session cookies. For example if you want to do a "confirm" page that spits back all the data that was entered before it gets submitted. You just echo all the session cookies like this: echo $_SESSION['post']['First_name']

On this "confirm" page – you can have a simple form with just a "confirm" and "go back" button. If you want people to be able to go back and edit their entries, you can make the fields in the form pages be "pre-populated" using the session cookie values like this:
First Name: <input type="text" name="First_Name" value="<?= $_SESSION['post']['First_Name']; ?>">

Unfortunately – checkboxes and dropdowns need to be handled differently. Because we're not displaying the value – we need to check each option – and if that's what had been selected, then we echo the text selected="selected"

To do the check you could do it "long hand" like this:<option value="NEW YORK" <?php if ($_SESSSION['post']['state'] == "NEW YORK") {
echo 'selected="selected"';
} ?> >NEW YORK</option>

and do that for each item – or you can do it the "shorthand" way – which I prefer for this much repetition – makes the code cleaner too:<option value="NEW YORK" <?php echo $_SESSION['post']['state']=='NEW YORK'?'selected="selected"':''; ?> >NEW YORK</option>

Another side note: the way that shorthand works is this:

CONDITIONAL_STATEMENT ? Do_this_if_true : Do_this_if_false

Once we're done updating the database, we'll want to clear out our session cookie:

<?php
unset($_SESSION['post']);
?>

7 Responses to "How to use Session Cookies in PHP"

1 | Keith

June 21st, 2007 at 8:25 am

Avatar

There is a quicker way to transfer the $_POST info into $_SESSION

These are both just arrays .. so

Instead of:

foreach($_POST as $k=>$v) {
$_SESSION['post'][$k]=$v;
}

You could use:

$_SESSION['post'] = $_POST;

Its less code, and not as processor intensive.

2 | will

July 10th, 2007 at 5:51 am

Avatar

Your method saves me a lot of time, as I am trying to convert a 600+ field form into a step-by-step process using PHP sessions. How do you apply this to a multi-page form (like, 5 pages, for example)? I can't get a form on the second page to append data to the session, then repeat that process for each step of the form.

3 | David

July 15th, 2007 at 1:17 pm

Avatar

This was very helpful. But what about radio buttons, where you have a default checked value? I'd like to have the form remember if they're using the checked value, or whether they selected another value. (You can see my form at http://www.meganhollingshead.com/contact.php.

Thanks.

4 | Jennifer

July 15th, 2007 at 9:02 pm

Avatar

Radio buttons in a series will have the same name – but the one checked will be the one that defines the value… so in your case, you have two radio buttons set as
name="contact"
So after you do the trick to transfer all the POST to SESSION – you can check for values, etc. using:
$_SESSION['post']['contact']
For example:
if ($_SESSION['post']['contact'] == "whateverTheDefaultValueIs") {
.....etc....

5 | Mark

February 12th, 2008 at 6:17 am

Avatar

Will, I was having the same trouble as you, I guess you used Keith's faster version as well. The problem with his method is that when you load the post data directly like that, you overwrite all the existing data.

If you use the original foreach method, you only overwrite duplicate field names, which is perfect for multipage forms.

6 | Jonathan

November 17th, 2008 at 1:16 pm

Avatar

Mark, rather than using the foreach method, just use the simple array operation + which accomplishes the same "overwrite duplicates" goal.

$_SESSION['post'] = $_POST + $_SESSION['post'];

7 | Mircea

January 14th, 2010 at 4:05 am

Avatar

I have 2 scripts and i would like to have the same signup/login for for both. The signup/login would be only on the first script , the second one will have disabled the forms.
So on the second one i just need them to appear as info where the case is. So when signup/login/edit i should have that info ( name, email, phone ) going to 2 databases.
Any ideas how could i do that ?
Would sessions help me ?

Featured Sponsors

Genesis Framework for WordPress

Advertise Here


  • Scott: Just moved changed the site URL as WP's installed in a subfolder. Cookie clearance worked for me. Thanks!
  • Stephen Lareau: Hi great blog thanks. Just thought I would add that it helps to put target = like this:1-800-555-1212 and
  • Cord Blomquist: Jennifer, you may want to check out tp2wp.com, a new service my company just launched that converts TypePad and Movable Type export files into WordPre

About


Advertisements