You are here: Home / Debian GNU/Linux / Servers / PHP / Store PHP sessions in Memcached

Store PHP sessions in Memcached

by Pierre-Yves Landuré last modified Nov 11, 2017 09:31

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


This howto needs :

Advantages and 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).


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.


Provide the IP address of Memcached server :


Provide the port of Memcached server :



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