Store PHP Session the other way via Memcached

Store PHP Session the other way via Memcached

Store PHP Session the other way via Memcached

Today i will show you how to Store PHP Session the other way via Memcached. If you decide to run PHP Apps on multiple Server Instances behind a Loadbalancer or having multiple Websites running on same Server and have no possibility to store your session data to a database for whatever reason you will realize that sharing a central file directory to store your PHP sessions to is also not a good idea. Surely you could solve this on one local server by using PHP-FPM adding custom session.save_path to each PHP Pool but that will not help if you have multiple Servers, since each Server writing on its own local session directory and will then cause a session inconsistency.

The Solution is using Memcached with PHP variable session.save_handler

I will describe the Steps on Debian based OS but this can also be adapted to any other OS.

Prerequisites:

  • Central Server with Memcached Package and Open TCP Port 11211
  • PHP5-Memcached Extension on every PHP Application Server

Install Memcached on a central System on which every PHP App Server can connect via Port 11211

apt-get install memcached

On the PHP Application Server install the Memcached Extension:

apt-get install php5-memcached

Go to your PHP Config Dir and modify the php.ini:

[Session]
session.save_handler = memcache
session.save_path = "tcp://yourMemcachedIP:11211"

You have also the ability to define the weight, timeout and retry interval for this Memcache connection.
So it looks like this then:

session.save_path = "tcp://yourMemcachedIP:11211?persistent=1&weight=1&timeout=1&retry_interval=15"

Restart your PHP Server (if PHP-FPM do):

service php-fpm restart

Restart your Webserver (if Nginx do):

service nginx restart

And you are Done!

Atleast one Important Note about using Memcached Session:

Bear in mind that you will lose all your Session Data in time or if your Memcached goes down or restarted. This is no permanent solution like local storage or database driven session save methods. MemcacheDB could also be a solution.
But for my purposes it is sufficient.

Rating: 5.0/5. From 1 vote.
Please wait...
Jules

Jules

Jules is the owner and author of ISPIRE.ME. He's a Linux System Engineer, Tech fanatic and an Open Source fan.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.