Page 1 of 1

variables and sessions

Posted: Wed Oct 08, 2003 6:19 pm
by wesnoel
Just wondering how I could save all the data from a form to a session variable as soon as a user navigates to another link. When they come back all of the form is field out to where they left off.

Is this posible?

I know cookies is another way but would rather stick to php, it also allows me to lean how to use sessions.

TIA,

Wes/

Posted: Wed Oct 08, 2003 7:31 pm
by McGruff
It's important to htmlspecialchars() any post vars which might get sent back to the form for security reasons and to take care of any quotes.

Setting session vars would go something like this:

Code: Select all

<?php
$_SESSION['var'] = htmlspecialchars($_POST['var']);
?>
To display previous entries in the form, you first need to check $_SESSION:

Code: Select all

<?php
if(isset($_SESSION['var']))
{
    $var = $_SESSION['var'];

} else {

    $var = null;
}
?>
Come to think of it, that should probably be a little fn:

Code: Select all

<?php
function getSessionVar($name)
{
    if(isset($_SESSION[$name]))
    {
        return $_SESSION[$name];

    } else {

        return null;
    }    
}

// in use
$var = getSessionVar('var');

?>
Finally, set the value attribute of form input fields to $var1, $var2 etc. If no corresponding session var was found, $vars have been set to null hence avoiding any "undefined index" errors.

General info on sessions:
viewtopic.php?t=6521

Posted: Thu Oct 09, 2003 12:07 pm
by wesnoel
Thank you McGruff,


I'll see if I can get that to work.

Wes/