PHP

sessionWrite

The sessionWrite( ) handler function isn't responsible only for writing variables to the session store but also records when session variables are read. sessionWrite( ) is called by PHP each time a variable is registered, when session variables change, and when a session is initialized. It's important that the last_access time-stamp is updated each time a session is initialized; that is, when session_start( ) is called. If the last access time isn't updated, a session may be seen as dormant by the garbage collection handler and destroyed even though the variables have recently been read.

Example D-5 starts by executing a SELECT query to determine if a session exists. If a session is found, then an UPDATE query is executed, otherwise a new session row is created with an INSERT query. Both the INSERT and UPDATE queries set the last_accessed field with the timestamp created by the support function getMicroTime( ) that is shown in Example D-2.

Example D-5. The sessionWrite handler
// This function is called when a session is initialized
// with a session_start(  ) call, when variables are
// registered or unregistered, and when session variables
// are modified. Returns true on success.
function sessionWrite($sess_id, $val)
{
  global $connection;
  global $session_table;
  $time_stamp = getMicroTime(  );
  $search_query =
    "SELECT session_id FROM $session_table
       WHERE session_id = '$sess_id'";
  // Execute the query
  if (!($result = @ mysql_query($search_query,
                                $connection)))
     showerror(  );
  if(mysql_num_rows($result) == 0)
  {
     // No session found, insert a new one
     $insert_query =
       "INSERT INTO $session_table
       (session_id, session_variable, last_accessed)
       VALUES ('$sess_id', '$val', $time_stamp)";
     if (!mysql_query($insert_query,
                      $connection))
        showerror(  );
  }
  else
  {
     // Existing session found - Update the
     // session variables
     $update_query =
       "UPDATE $session_table
        SET session_variable = '$val',
            last_accessed = $time_stamp
        WHERE session_id = '$sess_id'";
     if (!mysql_query($update_query,
                      $connection))
        showerror(  );
  }
  return true;
}

by BrainBellupdated
Advertisement: