10.2 Saving Sessions Using a Database


You want to save your session data in a database rather than saving it in the filesystem.

Technique

Use the session_set_save_handler() function to register functions that are working with the database:

 <?php // // 'sessions' table schema // create table sessions ( //   session_id char(32) not null, //   session_data text not null, //   session_expiration int(11) unsigned not null, //   primary key (session_id)); // include_once 'DB.php'; // Global Variables $dbh = NULL; function on_session_start ($save_path, $session_name) {     global $dbh;     $dbh = DB::connect('mysql://user:secret@localhost/SITE_SESSIONS',                        true);     if (DB::isError($dbh)) {         die(sprintf('Error [%d]: %s',                     $dbh->getCode(), $dbh->getMessage()));     } } function on_session_end () {    // Nothing needs to be done in this function    // since we used persistent connection. } function on_session_read ($key) {     global $dbh;     $stmt = "select session_data from sessions";     $stmt .= " where session_id = '$key'";     $stmt .= " and session_expiration > now()";     $sth = $dbh->query($sth);     $row = $sth->fetchRow(DB_FETCHMODE_ASSOC);     return $row['session_data']; } function on_session_write ($key, $val) {     global $dbh;     $val = addslashes($val);     $insert_stmt = "insert into sessions values('$key', '$val', now() + 3600)";     $update_stmt = "update sessions set session_data = '$val', ";     $update_stmt .= "session_expiration = now() + 3600 ";     $update_stmt .= "where session_id = '$key'";     // First we try to insert, if that doesn't succeed, it means     // session is already in the table and we try to update     if (DB::isError($dbh->query($insert_stmt)))         $dbh->query($update_stmt); } function on_session_destroy ($key) {     global $dbh;    $stmt = "delete from sessions where session_id = '$key'";    $dbh->query($stmt); } function on_session_gc ($max_lifetime) {     global $dbh;     // In this example, we don't use $max_lifetime parameter     // We simply delete all sessions that have expired     $stmt = "delete from sessions where session_expiration < now()";     $dbh->query($stmt); } session_start (); // Register the $counter variable as part // of the session session_register ("counter"); // Set the save handlers session_set_save_handler ("on_session_start",   "on_session_end",                           "on_session_read",    "on_session_write",                           "on_session_destroy", "on_session_gc"); // Let's see what it does $counter++; print $counter; session_destroy(); ?> 

Comments

The session_set_save_handler() function enables you to set up handler functions that the session system will call to perform the work of starting, ending, loading, and saving sessions.

The first argument of session_set_save_handler() is a function called by the session system when a session is first initialized . This function gets two arguments ”first the path where the session was stored (which is the same as the session.save_path setting) and then the name of the session cookie that was set (default is PHPSESSID ).

The next argument is the function called when the session is over (usually at the end of the script execution), and should be used to clean things up. This function receives no arguments.

The third argument to session_set_save_handler() is the function to execute when the session data needs to be read from the session store. The function receives the session ID as a function argument (that is, it receives something like f08b925af0ecb52bdd2de97d95cdbe6b ). The session id is a random number that is generated in order to make it harder for hackers to guess a session id (and therefore have access to a user's data).

The fourth argument of session_set_save_handler() is the function to execute when the session needs to save the data to the session store. The function specified in this argument is passed both the value of the current session ID (refer to the previous paragraph) and the session data as one string.

The fifth argument of session_set_save_handler() is the function to execute when the value of the session needs to be destroyed . The function specified in this argument is passed the value of the current session ID.

The sixth and last argument of session_set_save_handler() is the garbage collection function. It is called periodically by the session system to clean up old sessions that have expired. The function specified in this argument is passed the number of seconds after which the session data should be seen as stale and cleaned up.

The session_set_save_handler() function is the crux of customizing the session management features of PHP. Although it might not seem easy, play with it a little bit. Try some trivial scripts with the session_set_save_handler() , and you will see how easy it becomes.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net