Code to store PHP sessions within memcached.

Mauro N. Infantino mauroi at digbang.com
Fri Nov 17 13:32:35 UTC 2006


Keep in mind that the standard php session module locks the whole session
until the request finishes (or the user calls session_write_close) [1]. The
supplied could lead to problems when using frames or ajax (It's not thaaat
transparent. Even when not using frames it could happen, but it's less
probable). I could send the code implementing locking using memcache's add
method, if you want.

Regards,
Mauro.

[1] Take a look at
http://thwartedefforts.org/2006/11/11/race-conditions-with-ajax-and-php-sess
ions/
Under "Observing the Race Condition". Also, there are some code examples.

> -----Original Message-----
> From: memcached-bounces at lists.danga.com 
> [mailto:memcached-bounces at lists.danga.com] On Behalf Of Reinis Rozitis
> Sent: Friday, November 17, 2006 5:06 AM
> To: Memcached list
> Subject: Re: Code to store PHP sessions within memcached.
> 
> Hmm why dont you just use the nice feature of php to have 
> your own session 
> handling functions override the default which could be 
> transparent to the 
> rest of the code?
> We use something like this:
> 
> <?
> function mc_client() {
>  $smc =& $GLOBALS['smc'];
>  if (!is_object($smc)) {
>   $smc = new Memcache;
>   $smc->connect('127.0.0.1',11211);
>    // and the rest of the servers you need with memcache_add_server()
>  }
>  return $smc;
> }
> 
> function mc_ses_open($path, $name) { return true; }
> function mc_ses_close() { return true; }
> 
> function mc_ses_read($id) {
>  $client = mc_client();
>  return $client->get($id);
> }
> 
> function mc_ses_write($id,$data) {
>  $client = mc_client();
>  $client->set($id,$data,0,6000);
> }
> 
> function mc_ses_destroy($id) {
>  $client = mc_client();
>  $client->delete($id);
>  return true;
> }
> function mc_ses_gc($maxlt) { return true; }
> session_set_save_handler('mc_ses_open','mc_ses_close','mc_ses_
> read','mc_ses_write','mc_ses_destroy','mc_ses_gc');
> ?>
> 
> 
> And then simply session_start() and $_SESSION['blabla'] = 
> 'value' and thats 
> all.. (you dont need to stick with cookies cause that is 
> handled by default 
> from php side)
> 
> Tested on 30k concurent users/sessions online with 7 
> switching (roundrobin) 
> www nodes and it works just fine..
> The conclusion we got its best to keep some seperate 
> Memcached instance just 
> for the sessions that way you dont mix it with other type of 
> data caches and 
> because of LRU push the needed items out.
> 
> rr



More information about the memcached mailing list