home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Web Database Applications with PHP \& MySQLWeb Database Applications with PHP \& MySQLSearch this book

D.2. PHP Session Management

In Chapter 8 we showed how to build session-based applications using the PHP session management functions. Applications use these functions to initialize sessions and register session variables as shown in Example D-1. This simple script initializes a session and registers two session variables: count and start.

Example D-1. A simple PHP script that uses a session

  // Initialize a session. This call either creates 
  // a new session or re-establishes an existing one.
  session_start( );

  // If this is a new session, then the variable
  // $count is not registered
  if (!session_is_registered("count")) 

    $count = 0;
    $start = time( );

  $sessionId = session_id( );

   "-//W3C//DTD HTML 4.0 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd" >
    <p>This page points at a session 
        (<?=$sessionId ?>)
    <br>count = <?=$count ?>.
    <br>start = <?=$start ?>.
    <p>This session has lasted 
        $duration = time( ) - $start; 
        echo "$duration"; 

By default, PHP manages sessions by storing session variables in files on disk and uses the session ID as part of the filename. The session management functions and file storage are discussed in more detail in Chapter 8.

PHP allows user-defined handlers to be written that change how sessions are managed. The handlers define how PHP starts and terminates sessions, stores and retrieves session variables, and removes idle sessions with garbage collection. By implementing user-defined handlers, a developer can modify how PHP sessions are stored, without needing to change any application logic. PHP scripts, such as that shown in Example D-1, don't need to be modified except for an additional include directive to use the user-defined session management handlers.

D.2.1. PHP Session Management Storage Methods

Because PHP abstracts the storage method from the programmatic interface to session management, different storage strategies can be used. PHP can be configured to store session variables in files on disk (the default method), in memory, or in a user-defined way. The method used is configured by the session.save_handler parameter in the php.ini file. Here are the values the session.save_handler parameter can be set to:

This is the default storage method for PHP, where session variables are serialized and written to a session file.

The memory management storage method allows session variables to be stored in Apache's runtime memory. Using memory has the advantage of better performance than files on disk. However, if many sessions must be supported, and each session uses a large volume of data, the memory used by the Apache process may be high. To use memory to store session variables, Apache must be configured and compiled to use an installed memory management module (--with-mm).

The user-defined method allows an application to save session variables to systems other than file or memory, such as to a table in a database. By defining several handler prototypes, PHP allows the developer to define the behavior of the low-level session management. A full explanation is given in the next section.

D.2.2. Building User-Defined Session Handlers

When the PHP session.save_handler parameter is set to user, PHP expects to find functions that provide the low-level session management support. These are the functions the developer needs to write. The functions must conform to the defined prototypes:

Boolean open(string save_path, string session_name)
Called by PHP when session_start( ) or session_register( ) is called to access the session store. PHP passes the php.ini parameters session.save_path and session.name as arguments to this function, and these arguments are used to locate the session store. By default, session.save_path is set to /tmp to indicate the directory for the files storage method, and session.name is set to PHPSESSID as the name of the session ID cookie. These parameters select the database and table used to store session variables.

Boolean close( )
Called by PHP at the end of a script when a session is closed. The function should return false if an error occurs during the close operation and true on success.

mixed read(string session_id)
Called by PHP to read the variables for the session identified by session_id when a session is initialized. The function returns a string that contains the serialized session variables. The PHP engine converts the string to the individual session variables and sets up the $HTTP_SESSION_VARS array. If no session is found, the function should return a blank string. The function should return false if an error occurs during the read operation and true on success.

Boolean write(string session_id, string values)
This function is called by PHP when session variables are updated and when a session is initialized. This function is passed the ID of the session, and the session variables serialized into a single string by PHP. The implementation of write( ) must store the serialized string associated with the session, and record the time the session was last accessed. The serialized string stored for the session is returned by the read( ) handler. PHP uses this function not only to update session variables but to record the last access time when a session is initialized. The function should return false if an error occurs during the write operation and true on success.

Boolean destroy(string session_id)
Called by PHP when the session identified by session_id is destroyed. Removes storage dedicated to the identified session. The function should return false if an error occurs during the destroy operation and true on success.

Boolean gc(int max_lifetime)
Called by PHP with a probability set by session.gc_probability when a session is initialized. Removes the data and variables stored by dormant sessions. The value of session.gc_maxlifetime is passed to this function and is used to determine which are idle sessions. If the garbage collection handler is executed without error, it should return true.

While the return types and the parameters passed to the functions must conform to the prototypes listed here, the actual function names can be different. These functions need to be registered with PHP using session_set_save_handler( ):

session_set_save_handler(string open, string close, string read, string write, string destroy, string gc)
Registers a set of PHP function names as the callback functions for user-defined session management. The arguments to this function are the names of the functions. The six parameters passed to session_set_save_handler( ) are interpreted as the names of the open, close, read, write, destroy, and gc functions.

Once registered, PHP uses these handler functions when the PHP session management calls are made. The handler functions aren't called directly by scripts that use session management. More detail about these handlers is given later when we describe the MySQL storage implementations.

Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.