php sessions and memcache

Mauro Nicolas Infantino mauroi at digbang.com
Tue Jul 18 13:08:40 UTC 2006


That way, the client would have sensible information. Depending
on the application, it could be very insecure. If you use standard server 
sessions, the client only gets an id.

As I mentioned in that article in ajaxian, one possible way to avoid 
race conditions with memcached sessions, is to serialize (i mean, one
after another) the requests by locking the session. In this way works
PHP (uses flock exclusive on the session file) and it can be emulated
using add / increase / decrease with memcache. 

Something like:

class MemCacheSessionHandler
{
	var $_connection;
	
	function start() 
	{
		$connection =& MemCacheConnection::Connection();
		$this->_connection = &$connection;
		session_set_save_handler(	array(&$this, 'open'),
	
array(&$this, 'close'),
	
array(&$this, 'read'),
	
array(&$this, 'write'),
	
array(&$this, 'destroy'),
	
array(&$this, 'gc'));
		session_start();
	}

	function open($path, $name)
	{
		return true;
	}

	function close()
	{
		return true;
	}

	function read($id)
	{
		$connection = &$this->_connection;
		
		while (!$connection->add('sess_lock_' . $id, true,
ini_get('max_execution_time'))) usleep(200000);
		
		if ($data = $connection->get('sess_' . $id))
		{
			return $data;
		}
		else
		{
			return '';
		}
	}

	function write($id, $data)
	{
		$connection = &$this->_connection;
		
		return $connection->set('sess_' . $id, $data,
ini_get('session.gc_maxlifetime')) && $connection->delete('sess_lock_' .
$id);
	}

	function destroy($id)
	{
		$connection = $this->_connection;
		return $connection->delete('sess_' . $id) &&
$connection->delete('sess_lock_' . $id);
	}

	function gc($maxlifetime)
	{
		return true;
	}
}
$sessionHandler = new MemCacheSessionHandler();
$sessionHandler->start();
 

> Have you though about, for Ajax, not storing the session 
> state on the  
> server side. Surely the client side would be best placed to manage  
> user data, given that it is initiating all of the asynchronous  
> communications. I know that this would add extra bandwidth overheads  
> but maybe its worth it.
> 
> How does Google do it?
> 
> Matt



More information about the memcached mailing list