PHP

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.
session_set_save_handler("sessionOpen",
                         "sessionClose",
                         "sessionRead",
                         "sessionWrite",
                         "sessionDestroy",
                         "sessionGC");

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 session.name 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
session.name = 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 mysql_session.inc.

Example D-10. A simple PHP script that uses the MySQL session store
<?php
  // Include the MySQL session handlers
  include("mysql_session.inc");
  // 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"))
  {
    session_register("count");
    session_register("start");
    $count = 0;
    $start = time(  );
  }
  else
  {
    $count++;
  }
  $sessionId = session_id(  );
?>
<!DOCTYPE HTML PUBLIC
   "-//W3C//DTD HTML 4.0 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd" >
<html>
  <body>
    <p>This page points at a session
        (<?=$sessionId ?>)
    <br>count = <?=$count ?>.
    <br>start = <?=$start ?>.
    <p>This session has lasted
      <?php
        $duration = time(  ) - $start;
        echo "$duration";
      ?>
      seconds.
  </body>
</html>