Same name and namespace in other branches
  1. 4.6.x includes/session.inc \sess_write()
  2. 4.7.x includes/session.inc \sess_write()
  3. 5.x includes/session.inc \sess_write()

Writes an entire session to the database (internal use only).

This function is registered with session_set_save_handler() to support database-backed sessions.

This function is an internal function and must not be called directly. Doing so may result in corrupted session data or other unexpected behavior. Session data must always be accessed via the $_SESSION superglobal.

Parameters

$key: The session ID of the session to write to.

$value: Session data to write as a serialized string.

Return value

Always returns TRUE.

File

includes/session.inc, line 94
User session handling functions.

Code

function sess_write($key, $value) {
  global $user;

  // If saving of session data is disabled or if the client doesn't have a session,
  // and one isn't being created ($value), do nothing. This keeps crawlers out of
  // the session table. This reduces memory and server load, and gives more useful
  // statistics. We can't eliminate anonymous session table rows without breaking
  // the throttle module and the "Who's Online" block.
  if (!session_save_session() || $user->uid == 0 && empty($_COOKIE[session_name()]) && empty($value)) {
    return TRUE;
  }
  db_query("UPDATE {sessions} SET uid = %d, cache = %d, hostname = '%s', session = '%s', timestamp = %d WHERE sid = '%s'", $user->uid, isset($user->cache) ? $user->cache : '', ip_address(), $value, time(), $key);
  if (db_affected_rows()) {

    // Last access time is updated no more frequently than once every 180 seconds.
    // This reduces contention in the users table.
    if ($user->uid && time() - $user->access > variable_get('session_write_interval', 180)) {
      db_query("UPDATE {users} SET access = %d WHERE uid = %d", time(), $user->uid);
    }
  }
  else {

    // If this query fails, another parallel request probably got here first.
    // In that case, any session data generated in this request is discarded.
    @db_query("INSERT INTO {sessions} (sid, uid, cache, hostname, session, timestamp) VALUES ('%s', %d, %d, '%s', '%s', %d)", $key, $user->uid, isset($user->cache) ? $user->cache : '', ip_address(), $value, time());
  }
  return TRUE;
}