memcached

Using memcached to share PHP sessions

Posted in apache, memcached, php on July 29th, 2010 by fseek – Be the first to comment

This tutorial explains how to install and configure memcached to share PHP sessions across multiple servers (all running CentOS).

One of my sites was outgrowing the cheap VPS server that we were paying for it. Instead of adding more memory/CPU, we decided to add more servers to the equation, sharing the load between them.

To do that, we started to use memcached. Memcached is very simple to use and install and is easy to integrate with PHP. Let’s get to work!

1- Installing memcached.

Memcached has some prebuilt packages for Ubuntu, but none that I could find the CentOS. Because of that, I had to install it manually from the source. It is simple as well, just follow these steps:

1.0 – Installing pre-requisites:

# yum install libevent-devel.i386
# yum install php-pecl-memcache.i386

1.1-Downloading:

# wget “http://memcached.googlecode.com/files/memcached-1.4.5.tar.gz”
# tar -zxvf memcached-1.4.5.tar.gz
# cd memcached-1.4.5

1.2-Compiling

# ./configure
# ./make && make test
# ./make install

1.3- Running it

# /usr/sbin/useradd memcached
# /usr/local/bin/memcached -d -u memcached

You see that we installed it at /usr/local/bin and created a restricted user for it. Now you should have memcached running. Just run “netstat -tanep” to check.

2- Configuring PHP

2.1 – Via php.ini

If you have access to the php.ini (like we had in one of our servers), just add the following to it:

session.save_handler = memcache
session.save_path=”tcp://serverA:11211″

After restarting Apache, PHP will use memcached that we installed on the “serverA”. That’s all.

2.2 – Via modifications in the php scripts

If you can’t modify your php.ini, add the following to your php scripts:

ini_set(’session.save_handler’, “memcache”);
ini_set(’session.save_path’, “tcp://serverA:11211″);

That’s it as well. If you are having problems with the sessions, make sure to use the same session name across servers:

ini_set(’session.cookie_domain’, “.domain.com”);
session_set_cookie_params(0, ‘/’, ‘.domain.com’);
session_name(“SESSIONX”);
session_start();

That’s it. Easy, no?