Adding session data

All your session data is stored in the session superglobal array, $_SESSION, which means that each session variable is one element in that array, combined with its value. Adding variables to this array is done in the same way as adding variables to any array, with the added the bonus that session variables will still be there when your user browses to another page.

To set a session variable, use syntax like this:

$_SESSION['var'] = $val;
$_SESSION['FirstName'] = "Jim";

Older versions of PHP used the function session_register(), however use of this function is strongly discouraged, as it will not work properly in default installations of PHP 5. If you have scripts that use session_register(), you are strongly recommended to switch over to using the $_SESSION superglobal, as it is more portable, and easier to read too.

Before you can add any variable to a session, you need to have already called the session_start() function - don't forget!

Author's Note: you cannot store resources such as database connections in sessions, nice as that might be, because these resources are unique to each PHP script, and are usually cleaned when that script terminates. While this may change in the future, it is not likely.


Next chapter: Reading session data >>

Previous chapter: Starting a session

Jump to:


Home: Table of Contents

Follow us on or Twitter

Username:   Password:
Create Account | About TuxRadar