You are here

function sess_read in Drupal 6

Same name and namespace in other branches
  1. 4 includes/session.inc \sess_read()
  2. 5 includes/session.inc \sess_read()

Reads an entire session from the database (internal use only).

Also initializes the $user object for the user associated with the session. This function is registered with session_set_save_handler() to support database-backed sessions. It is called on every page load when PHP sets up the $_SESSION superglobal.

This function is an internal function and must not be called directly. Doing so may result in logging out the current user, corrupting 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 retrieve.

Return value

The user's session, or an empty string if no session exists.

1 string reference to 'sess_read'
_drupal_bootstrap in includes/bootstrap.inc

File

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

Code

function sess_read($key) {
  global $user;

  // Write and Close handlers are called after destructing objects since PHP 5.0.5
  // Thus destructors can use sessions but session handler can't use objects.
  // So we are moving session closure before destructing objects.
  register_shutdown_function('session_write_close');

  // Handle the case of first time visitors and clients that don't store cookies (eg. web crawlers).
  if (empty($key) || !isset($_COOKIE[session_name()])) {
    $user = drupal_anonymous_user();
    return '';
  }

  // Otherwise, if the session is still active, we have a record of the client's session in the database.
  $user = db_fetch_object(db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = '%s'", $key));

  // We found the client's session record and they are an authenticated,
  // active user.
  if ($user && $user->uid > 0 && $user->status == 1) {

    // This is done to unserialize the data member of $user
    $user = drupal_unpack($user);

    // Add roles element to $user
    $user->roles = array();
    $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
    $result = db_query("SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = %d", $user->uid);
    while ($role = db_fetch_object($result)) {
      $user->roles[$role->rid] = $role->name;
    }
  }
  else {
    $session = isset($user->session) ? $user->session : '';
    $user = drupal_anonymous_user($session);
  }
  return $user->session;
}