User:Jonathans/mcs

check this sumbitch out. this took like five minutes to write. memcache frigging rules! <?php /* -*- C++ -*- */

/** * custom session save handler * * @id $Id$ * @precondition: $memcache is a valid memcache object connected to at least one server. * @precondition: this file is always included before session_start is called. * @postcondition: php sessions are stored in memcache. * * set session.save_path to better obscure the location of the session data in cache. * * garbage collection is done with session.maxlifetime by passing expiry to memcache. * note that this means memcache will do its own gc even if gc_probability = 0. */

$g_session_save_path = null; $g_session_name = null; $g_session_timelimit = 0;

function mcs_key($key) { global $g_session_save_path; return $g_session_save_path. ':' . $key; }

// called on session_start // function mcs_open($save_path, $session_name) { global $g_session_save_path, $g_session_name, $g_session_timelimit; $g_session_save_path = $save_path; $g_session_name     = $session_name; $g_session_timelimit = (int)ini_get('session.maxlifetime'); return true; }

// nothing to do, because memcache rules! // function mcs_close { return true; }

// called on session_start. // any new or invalid session read implies $_SESSION=array instead of NULL // php implements this function similar to the statement: //  $_SESSION = mcs_read(session_id); // function mcs_read($session_id) { global $memcache; $sdata = $memcache->get(mcs_key($session_id)); return ($sdata === false) ? array : $sdata; }

// called on session_write_close, etc. // function mcs_write($session_id, $session_data) { global $memcache, $g_session_timeout; return $memcache->set(mcs_key($session_id), $session_data, 0, $g_session_timeout); }

// called on session_destroy // kaboom // function mcs_destroy($session_id) { global $memcache; $memcache->delete(mcs_key($session_id)); // the following line is optional, and changes the default behavior of PHP, // but it saves having to remember to do this, and a bit of typing, whenever // you manually call session_destroy. $_SESSION = array; return true; }

// nothing to do, because memcache rules! // function mcs_garbage($max_lifetime) { return true; }

// set that shit son // session_set_save_handler('mcs_open', 'mcs_close', 'mcs_read', 'mcs_write', 'mcs_destroy', 'mcs_garbage'); ?>