fluidthoughts developers' guild

fluid funk

howto / php / sessions

Working with sessions in PHP

PHP session management addresses the long standing academic problem over how to maintain user-state information in a stateless http environment.

There are 2 ways of doing this on your own:

A) Assign a session ID and pass it around with GET/POST variables

Unfortunately, this is vulnerable to user manipulation and doesn't allow for human-readable URIs.

B) Assign a cookie to be read by each page

Not all users will have cookies turned on, and is an inappropriate solution when your audience may be browsing in a multi-user environment such as a computer lab or library.

PHP 4+ has built-in session management

Sessions work by preserving the state of variables from page to page by tying them to a unique session ID on the server. A temporary file is created for the lifetime of the session, and all registered session variable information is written to that file.

You can work with sessions easily, and transparently. An example of session-dependent hit counter is an easy example of how to work with sessions.

Session functions:

If you are using a session, it needs to be started and registered before anything is printed out to the screen.

session_start();

This begins a session, using an md5 hash to uniquely create an ID number.

session_register("count");

Any variables to be used in the session need to be registered. You can register any variables you like, but these can get out of control if you don't remember what they were called. It might be easiest to simply use an associative array, or object named SESSION to store all the neccessary values in.

That session ID is stored within the client's session-cookies (which go away when you quit the browser). These files are written to a file in /tmp and look like this:

/tmp/sess_b7207e7f3f45b798a974c2ca72531e1b
SESSION|a:1:{s:5:"count";i:2;}

Essentially what you would see if you were to "serialize" that hash table.

more references:
http://www.php.net/manual/en/ref.session.php
http://www.zend.com/zend/tut/session.php

 

$Id: sessions.html,v 1.4 2006/11/04 00:00:38 willn Exp $