PHP

Handler Implementations

The best way to arrange the functions that implement the session handlers is to place them in a single support file. By placing the functions shown in Example D-2 through Example D-9 in the one file, you can include that file at the beginning of any PHP script using sessions. The support file containing the handler implementations-for example mysql_sessions.inc-must be included before any session calls are made as shown in the following example:

<?php
  include("mysql_sessions.inc");
  start_session(  );
  //... rest of script ...
?>

Support functions

The MySQL-based session handlers use the showerror( ) function implemented in the error.inc include file, and the $hostName, $username, and $password variables set in the db.inc include file. The showerror( ) function is used by the handler implementations to display details about MySQL errors. The db.inc file provides a central location for maintaining connection details. The error.inc and db.inc files are described in Chapter 4.

Example D-2 shows the function getMicroTime( ), which generates a timestamp. The timestamp records the last session access in the sessionWrite( ) handler and creates a query that identifies idle sessions in the sessionGC( ) handler. The sessionWrite( ) handler and the sessionGC( ) handler are developed later in this section.

Example D-2. The support function getMicroTime( )
include("error.inc");
include("db.inc");
// Returns current time as a number.
// Used for recording the last session access.
function getMicroTime(  )
{
  // microtime(  ) returns the number of seconds
  // since 0:00:00 January 1, 1970 GMT as a
  // microsecond part and a second part.
  // e.g.: 0.08344800 1000952237
  // Convert the two parts into an array
  $mtime = explode(" ", microtime(  ));
  // Return the addition of the two parts
  // e.g.: 1000952237.08344800
  return($mtime[1] + $mtime[0]);
}

by BrainBellupdated
Advertisement: