The sessionRead( ) handler function-shown in Example D-4-is called by PHP each time a session is initialized. The handler returns the serialized string that holds the session variables for the given session ID $sess_id. The function executes a query to find the row with a session_id equal to $sess_id and, if the row is found, the session_variable attribute is returned. If no session is found, sessionRead( ) returns a blank string. If an error occurs when the SELECT query is executed, showerror( ) is called.

The query is constructed using the global variables $session_table and executed using the global variable $connection set up by the sessionOpen( ) handler. Note that this function returns all the session variables in the one serialized string. The calling PHP code converts the string to the individual session variables and sets up the $HTTP_SESSION_VARS array and the associated global variables if register_globals has been enabled.

Example D-4. The sessionRead handler
// This function is called whenever a session_start(  )
// call is made and reads the session variables
// Returns "" when a session is not found
//         (serialized)string - session exists
function sessionRead($sess_id)
  // Access the DBMS connection
  global $connection;
  // Access the global variable that holds the name
  // of the table that holds the session variables
  global $session_table;
  // Formulate a query to find the session
  // identified by $sess_id
  $search_query =
    "SELECT * FROM $session_table
      WHERE session_id = '$sess_id'";
  // Execute the query
  if (!($result = @ mysql_query($search_query,
     showerror(  );
  if(mysql_num_rows($result) == 0)
    // No session found - return an empty string
    return "";
    // Found a session - return the serialized string
    $row = mysql_fetch_array($result);
    return $row["session_variable"];

by BrainBellupdated