Friday, December 03, 2004

[tech] PHP session management functionality

PHP Session modules allows you to keep track and access all kinds of variables that you can to have access to for the duration of the user session.

This functionality could be implemented by embedding a long list of variables from page to page. But, man, PHP session is so much easier.

To start a session, just call session_start(). You MUST put this call at the top of your file, before any other output to the browser.

Creating session variable is a breeze. For example, to want to store the username that I received from the login form: $_SESSION['username'] = $_POST['username'];.

To access the session variable in subsequenc files, you MUST start the file with call to session_start(). That function will magically figure out the current session data and populate $_SESSION array, so you can say, access $_SESSION['username']. (see www.php.net/session-start on how the magic happens)

By default, PHP session stores session data in files, as specified in the session.save_path vars in php.ini. PHP session has a flexible architecture where you can extend it to store session data in DB.

If you don't remember where your php.ini is --- use phpinfo() find out.

If you don't think your session is working --- Check you php/logs/php_error.log for any errors, or check the session.save_path vars and make sure the directory exists, is writable, and you see new sess* files being created there.