Memcached as a PHP Session Handler

Memcached makes a semi-perfect solution for storing your PHP sessions. Why only semi-perfect? Well in Memcached’s defense, the fact that it is an in-memory data store makes it a great choice because of the speed. The negative is the lack of persistence, which makes it somewhat less desirable. What this means if that if you run into a scenario where you either need to reboot your server or your Memcached instance, you will end up logging all of your users out forcing them to log back in again. Another scenario would be filling up the memory you allocated for Memcached. Same problem, to allocate more memory you would need to reconfigure Memcached and restart it (assuming you can’t just add in another Memcached server and cluster them).

That being said, now that you know the risks, let’s show you how to use Memcached as your session handler. To do so, you will need to set the session’s save handler and save path which can be done right in php.ini (if you’d like to make it a global change):

session.save_handler = memcache
session.save_path    = tcp://

or right in your code:

ini_set('session.save_handler', 'memcache'
ini_set('session.save_path',    'tcp://'

That’s all there is to it to start using Memcached on your web server to store PHP sessions. Please keep in mind that the above examples show memcache but there is also another PHP extension for Memcached called memcached. It’s still somewhat of a controversy as to which one is better, but either should be sufficient based on which you have available on your server.

In addition to the host and port, there are a few other options you can use (in query string format but be sure to encode & as &). Those options include persistent which can be 1 or 0, weight to specify the weight of the server when multiple servers are specified, timeout and retry_interval which are self explanatory, Speaking of multiple servers, if you have multiple Memcached servers in a cluster / pool you can utilize them all by adding them all to the save_path, comma separated.

Tomorrow I’ll discuss using a more persistent in-memory data store that I consider significantly more ideal!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

If you found this article helpful, please consider buying me a coffee.