Storing your PHP sessions using Memcached   Recently updated !


Memcached is a high-performance, distributed memory object caching system. Many big well-known sites use it to store their PHP sessions in a centralized way and to reduce the load on their servers.

Installation with Apache2 and PHP5 on Debian:

Install these packages (if memcached is on a different server, omit the package):

apt-get install memcached php5-memcached

Then make sure to load the new php module by creating the ini file:

echo "extension=memcached.so" > /etc/php5/conf.d/memcached.ini

Next we need to modify the php.ini file, which should be by default located here: /etc/php5/apache2/php.ini

Now go on with the "Common steps" section below!

Installation with Zend Server on Debian:

Install these packages (if memcached is on a different server, omit the package):

apt-get install memcached php-5.3-memcached-zend-server

The package name for zend-server might vary depending on your php-version (php-5.4-memcache-zend-server, php-5.5-memcache-zend-server with Zend Server 7)

Then make sure to load the new php module by creating the ini file and linking it:

echo "extension=memcached.so" > /usr/local/zend/etc/ext.d/memcached.ini
ln -s /usr/local/zend/etc/ext.d/memcached.ini /usr/local/zend/etc/ext.d/memcached.ini

Next we need to modify the php.ini file, which should be by default located here:  /usr/local/zend/etc/php.ini

Now continue with the "Common steps" below!

Common steps after both of the above installations:

Having located the php.ini file in the preceding step, we're going to do the important modifications in there now.

Modify the line starting with session.save_handler and replace file with memache: session.save_handler = memcached

Now replace the line starting with session.save_path with the following (remove the trailing ";" if exists):

session.save_path="tcp://127.0.0.1:11211"

Think of replacing the IP address 127.0.0.1 with the one of your Memcached server if it does not match your localhost.

Finally restart Apache to make your changes take effet: /etc/init.d/apache2 restart

Depending on the traffic and the number of sessions, you should see some statistics growing:

echo "stats" | /bin/netcat -q 2 127.0.0.1 11211

Verify that your sessions are stored in Memcached:

Use telnet to connect to your running memcached service:

telnet localhost 11211

Type:

stats items

which will output you something similar to this:

STAT items:3:number 1
STAT items:3:age 233
STAT items:3:evicted 0
STAT items:3:evicted_nonzero 0
STAT items:3:evicted_time 0
STAT items:3:outofmemory 0
STAT items:3:tailrepairs 0
STAT items:3:reclaimed 0
STAT items:3:expired_unfetched 0
STAT items:3:evicted_unfetched 0
END

The number after items: is called "slab id". Now type for example:

stats cachedump 3 100

to dump a maximum of 100 cache key entries for slab_id 3. Session entries usually look like this:

ITEM memc.sess.key.9cbqk2c4t200krtdhpdse7boc1 [33 b; 1415203613 s]