tags:

views:

20

answers:

2

I have several stages to an application process consisting of multiple forms on different pages.

I have created a session to handle the data.

My question is, without explicitly stipulating every form field form can i add the form post to an individual part of the session array one by one.

So that when im at the end i can just loop through and print?

A: 

I'm a little unclear but I think you're saying you want a single array of all your form variables from each page. Something like this should do the trick:

if( !isset($_SESSION['form_data']) ) { 
     $_SESSION['form_data'] = array();
}
$_SESSION['form_data'] = array_merge($_SESSION['form_data'], $_POST );

You would put that as the code to handle the submit on each page and then of course the last page you could loop through $_SESSION['form_data']

Note that any form fields having the same name will get overwritten each time they are used. So if you had name on page 1 and name on page 2. The value of name from page 2 would end up in the array

For security though you should check your input data even before putting it into the session.

Cfreak
Thanks for this! Very useful!
Andy
A: 

Sure, you could do something like this:

foreach($_POST as $key => $value)
    $_SESSION['form'][$key] = $value;

This will save all the POST data into the $_SESSION['form'] array. Note that it saves all the data, a malicious user can just add values to this.

On the last page you can echo the fields like this (don't forget to escape the values, that's what htmlspecialchars() is for).

foreach($_SESSION['form'] as $key => $value)
    echo htmlspecialchars($key) . ": " . htmlspecialchars($value) . "<br />\n";

Edit: The array_merge() approach is acutaly more elegant than this one, so just forget about the first piece of code.

svens
Very cool! Thanks both of you guys!
Andy
So i could just post this on every page with the respective $_SESSION['form'] changes.
Andy