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 is removed in modern versions of PHP. 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.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Reading session data >>

Previous chapter: Starting a session

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.