Hudzilla.org - the homepage of Paul Hudson
Contents > Cookies and Sessions > Using sessions Wish List | Report Bug | About Me ]

10.3.2     Adding session data

This is NOT the latest copy of this book; click here for the latest version.

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.





<< 10.3.1 Starting a session: session_start()   10.3.3 Reading session data >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
Be the first to add a comment to this chapter!



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is four plus four?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow