The minute a PHP application develops to keep running on more servers, ordinarily people will see issues caused by PHP sessions. If you are using two or more server for your application using load balancer you will need to enable stickiness (sending the users to the same real server) to handle the users request. If you do not care load balancer this will slowly become a major issue.
There are lots of way to store PHP session in a shared location, but in this tutorial I will show you simple way to store PHP session in memcached.
Store PHP Session in Memcached
The pecl memcache php extension has supported for a long time the memcache session.save_handler, but with the release 3.0.x this brings in a set of interesting features for us: – UDP support – Binary protocol support – Non-blocking IO using select() – Key and session redundancy (values are written to N mirrors) – Improved error reporting and fail-over handling.
Install PHP Memcache Module
First of all you will need to install php memcache module using distribution repositories. You can also install php memcache using pecl or manual compilation.
# pecl install memcache-3.0.4
# wget http://pecl.php.net/get/memcache-3.0.4.tgz # tar xvfz memcache-3.0.4.tgz # cd memcache-3.0.4 # phpize # ./configure # make # make install
Once installation completed, edit the php.ini file to enable the module. I prefer to create a new file for this memcache.ini inside the include directory of the php build. For example in Debian this is under /etc/php5/conf.d/memcache.ini) and for rpm based this is under /etc/php.d/memcache.ini. Put the below lines in memcache.ini.
extension=memcache.so memcache.allow_failover = 1 memcache.redundancy = 1 memcache.session_redundancy = 2
To store the php session in memcache you will need to edit php.ini file and replace the default file handler setting with something like below:
; Use memcache as a session handler session.save_handler = memcache ; Use a comma separated list of server urls to use for storage: session.save_path="udp://:11211?persistent=1&weight=1&timeout=1&retry_interval=15"
You can also define it inside the php block if you do not want to use this on server side.
$session_save_path = "tcp://:11211?persistent=1&weight=1&timeout=1&retry_interval=15, tcp://:11211"; ini_set('session.save_handler', 'memcache'); ini_set('session.save_path', $session_save_path);
Finally restart the Apache service to start using the memcache to store the php sessions.
# service httpd restart