Store PHP sessions in Memcached
By default, PHP sessions are stored on file system (in /var/lib/php5, or in /tmp). If the hosted PHP sites have an intensive use of sessions, this can add a additional delay to PHP requests run. It is possible to optimize PHP performances by storing sessions in memory with the help of Memcached. This guide describe how to set this up.
This howto is tested on :
- Debian 6.0 Squeeze
Prerequisites
This howto needs :
- a working PHP setup, as described by Install PHP-FPM on Debian.
- a Memcached server, as described by Install Memcached on Debian.
Advantages and drawbacks
Drawbacks
Using Memcached to store sessions set these limitations :
- Stored sessions can't raise over 1 MB in size.
- The sessions are not persistent, and a restart of Memcached daemon delete them.
- It is impossible to control sessions duration.
- The number of managed sessions is limited by the size of Memcached cache.
Do not use Memcached to store PHP sessions if the sessions contains sensible datas (in case of a E-commerce website for example).
Advantages
Using Memcached to store session add these advantages :
- The access to session data is very quick, because of in-memory storage.
- There is no need of a obsolete sessions deletion mecanism, Memcached handle it.
- In the limit of Memcached cache size, the system can easily manage over ten of thousands of concurrent sessions.
Parameters
Provide the IP address of Memcached server :
MEMCACHED_IP="127.0.0.1"
Provide the port of Memcached server :
MEMCACHED_PORT="11211"
Installation
Install the PHP5 module for Memcache :
command apt-get install php5-memcached
Note : Many howtos available on Internet use php-memcache over php5-memcached. php-memcached is recommanded as it is more recent and has more features.
Setup PHP5 to store sessions in Memcached server :
command echo "; Storing session in memcached server.
session.save_handler = memcached
session.save_path=\"${MEMCACHED_IP}:${MEMCACHED_PORT}\"" \
> '/etc/php5/conf.d/sessions-store-memcached.ini'
Reload PHP configuration :
test -x /etc/init.d/php5-fpm && /etc/init.d/php5-fpm force-reload
test -x /etc/init.d/apache2 && /etc/init.d/apache2 force-reload
test -x /etc/init.d/lighttpd && /etc/init.d/lighttpd force-reload
test -x /etc/init.d/nginx && /etc/init.d/nginx force-reload
Thanks
- Thanks to Hio.fr (fr) for PHP session avec memcached (fr).
- Thanks to Artur Ejsmont (en) for PHP session in Mysql VS Memcached (en).