You are here

function sess_write in Memcache API and Integration 5.2

Same name in this branch
  1. 5.2 session-memcache.inc \sess_write()
  2. 5.2 session-memcache-db.inc \sess_write()
  3. 5.2 session-memcache.db.inc \sess_write()
Same name and namespace in other branches
  1. 5 memcache-session.inc \sess_write()
  2. 6 memcache-session.inc \sess_write()

File

./session-memcache.db.inc, line 55
User session handling functions.

Code

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

  // If the client doesn't have a session, and one isn't being created ($value), do nothing.
  if (empty($_COOKIE[session_name()]) && empty($value)) {
    return TRUE;
  }

  // If we have a session in memcache, lets keep track.
  $in_memcache = dmemcache_get($key, 'session');
  if (!$in_memcache) {
    $result = db_query("SELECT sid FROM {sessions} WHERE sid = '%s'", $key);
    $in_db = db_num_rows($result);
  }
  if (!$in_memcache && $user->uid) {

    // Prepare the information to be saved
    $info = new stdClass();
    $info->sid = $key;
    $info->uid = $user->uid;
    $info->cache = $user->cache;
    $info->hostname = $_SERVER["REMOTE_ADDR"];
    $info->session = $value;
    $info->timestamp = time();
    $put_in_memcache = dmemcache_set($key, $info, ini_get('session.gc_maxlifetime'), 'session');
  }

  // First time the browser sends back the cookie, save to both db and memcache in case of memcache failure
  if (!$in_db && !$in_memcache && ($user->uid || $value || count($_COOKIE))) {
    db_query("INSERT INTO {sessions} (sid, uid, cache, hostname, session, timestamp) VALUES ('%s', %d, %d, '%s', '%s', %d)", $key, $user->uid, $user->cache, $_SERVER["REMOTE_ADDR"], $value, time());
  }
  else {

    // On memcache_set failure, we update the database
    if (!$in_memcache && !$put_in_memcache) {
      db_query("UPDATE {sessions} SET uid = %d, cache = %d, hostname = '%s', session = '%s', timestamp = %d WHERE sid = '%s'", $user->uid, $user->cache, $_SERVER["REMOTE_ADDR"], $value, time(), $key);
    }

    //Let's only update every 5 minutes for now.

    /*
    if(variable_get('session_access_update', 0) < time()) {
      db_query("UPDATE {users} SET access = %d WHERE uid = %d", time(), $user->uid);
      variable_set('session_access_update', time() + 300);
    }
    */
  }
  return TRUE;
}