[thelist] php sessions

Peter Johansson peter at johansson.org
Wed Oct 16 00:41:01 CDT 2002

On Tue, 15 Oct 2002, Michele Wandrei wrote:

> Make sure that you give your session variables names that are
> different from the variables you use within the page!  I created
> a user login system, registering person_id as a session variable
> to track my user across scripts.  Well, one of the pages that
> users can access is a directory listing of other names that
> includes person_id.  When the registered user visited this page,
> the value of the session variable person_id was replaced with the
> last value of person_id that appeared on that page.  It's one of
> those "duh" lessons that I won't forget!

And to take that one step further:

<tip type="php sessions" author="peter johansson">

One way to avoid those kind of problems is to always use the superglobal
array $_SESSION that's available in more recent versions of PHP. This can
be used both when writing to the session and reading from it.


// Add something to the session
$_SESSION['user_id'] = 42;

// Read a value from the session
if ( $_SESSION['user_id'] == 42 ) {
	// do something


- Selfdocumented code, you can instantly tell whether a variable is a
session variable or some other kind of variable.
- You don't accidently mix up your session variables with your other
local/global variables.



More information about the thelist mailing list