Registering session handlers

Finally, the handlers implemented in Example D-3 through Example D-8 need to be registered as callback functions with PHP. Example D-9 shows the call to session_set_save_handler( ) with the names of each handler function.

Example D-9. Registering the user-defined session handlers with PHP
// Call to register user call back functions.

Using the User-Defined Session Handler Code

Once the user-defined session handler code is implemented, it can be used by setting up the session configuration in the php.ini file and including the library at the top of PHP scripts that use sessions. The session.save_handler parameter needs to be set to user, indicating that user-defined handlers are used; the session.save_path parameter is set to the name of the database; and parameter is set to the name of the table. The following example settings are used if session variables are stored in the PHPSESSION table of the winestore database:

session.save_handler = user
session.save_path = winestore = PHPSESSION

Example D-10 shows how application scripts are modified to use the MySQL session store; the script is a copy of Example D-1, with the addition of the directive to include

Example D-10. A simple PHP script that uses the MySQL session store
  // Include the MySQL session handlers
  // 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"
   "" >
    <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 BrainBellupdated