// Tutorial //

How To Store PHP Sessions in Memcached on a CentOS VPS

Published on August 5, 2013
Default avatar
By Tim Kotkamp
Developer and author at DigitalOcean.
How To Store PHP Sessions in Memcached on a CentOS VPS

About Memcached

Memcached is an in-memory key-value store for small chunks of arbitrary data (strings, objects) from results of database calls, API calls, or page rendering.

Why store sessions in Memcached?

Memcached will store sessions in memory instead of files. Because memory is way faster than reading a file your website will perform better and reduce load time.

What's the catch?

Sessions will only be stored in memory, memory can't hold data when your VPS is turned off or gets restarted so sessions will be deleted upon shutdown.

Setup

Before starting this tutorial, make sure you have an up and running PHP 5 installation, you can find tutorials on how to do this in the PHP help section.

Make sure you have the EPEL repository installed, you need the EPEL repository for Memcached because Memcached isn't available in the base repository.

rpm -Uvh http://mirrors.kernel.org/fedora-epel/6/x86_64/epel-release-6-8.noarch.rpm

Updating packages to the latest available version isn't required but recommended.

yum update

Installing Memcached

Lets start with installing Memcached.

yum install memcached

After installing Memcached, open the configuration file of Memcached with VI.

vi /etc/sysconfig/memcached

You will see this:

PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS=""

Memcached isn't protected with a password or username so anyone can access it through port 11211. We don't want this so we are going to allow only your VPS to access it by inserting some options in the 'OPTIONS=' section:

PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS="-l 127.0.0.1"

You might want to change the cachesize; by default it is 64MB. As soon as Memcached reaches this limit, it will delete old entries to free up memory for new entries. Unless you have a very huge website, 64MB should be fine.

Lets start Memcached.

/etc/init.d/memcached start

Memcached doesn't start by default upon boot, we want it to start upon boot.

chkconfig --levels 235 memcached on

Installing the Memcached PHP Extension

We need to install a few things, lets start with the development tools. These are required to build from the source code:

yum groupinstall "Development Tools"

After that, we are going to install a few more things. The first two are required to build the extension, and the last two are required to run / install the extension in PHP.

yum install zlib-devel libmemcached-devel php-pear php-pecl-memcached

Now we are going to install the PHP Memcached extension using PECL (PHP Extension Community Library) which we have just installed.

pecl install -f memcached-1.0.0

Changing PHP.ini to Setup Memcached as Session Handler

The last thing to do is to configure PHP to use Memcached as session handler. To do so, you have to open /etc/php.ini with VI.

vi /etc/php.ini

Search for the '[Session]' area as displayed below (scrolling from bottom to top is easier).

[Session]
; Handler used to store/retrieve data.
; http://www.php.net/manual/en/session.configuration.php#ini.session.save-handler
session.save_handler = files

And change it to this:

[Session]
; Handler used to store/retrieve data.
; http://www.php.net/manual/en/session.configuration.php#ini.session.save-handler
session.save_handler = memcached
session.save_path = "127.0.0.1:11211"

As you can see, we've changed the session_handler to memcached and the path to our localhost on port 11211 on which Memcached operates. Now lets restart Apache to reload the PHP.ini file.

service httpd restart

All sessions are now stored in Memcached instead of files.

You may see the following error:

Starting httpd: httpd: apr_sockaddr_info_get() failed for memcached
httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

You can resolve this by editing the apache configuration:

vi /etc/httpd/conf/httpd.conf

and uncomment the ServerName line:

ServerName localhost

More with Memcached

Memcached is ideal for storing intensive queries which doesn't need to be in realtime on every page view but in specified time increments (ie. every 10 minutes). For more information on how to use Memcached inside your scripts, I recommend you to look at step three in this tutorial.

Submitted by: Tim Kotkamp

If you’ve enjoyed this tutorial and our broader community, consider checking out our DigitalOcean products which can also help you achieve your development goals.

Learn more here


About the authors
Default avatar
Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?
10 Comments

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

you forgot:

yum install php-devel (for me that was the only thing missing) ;)

and: pecl install memcache (optional, but good to have, for wordpress users, as they will want to use w3 total cache and for some strange reason once pecl memcache is installed, w3 total cache starts showing it in options, personal experience)

Hello, I have no results to fix working memcached. The follow error come up:

memcached: invalid option – ‘1’ Illegal argument “?” (When I have set the settings to “-1 127.0.0.1”)

Nice tutorial, thnx. But I have some problems to install memcached on a VPS cloud server CentOS 6.2 x64 Using memcached on PrestaShop version 1.6.1.1 The follow fault:

[root@vps ~]# pecl install -f memcached downloading memcached-2.2.0.tgz … Starting to download memcached-2.2.0.tgz (70,449 bytes) …done: 70,449 bytes 15 source files, building running: phpize Configuring for: PHP Api Version: 20100412 Zend Module Api No: 20100525 Zend Extension Api No: 220100525

configure: error: no, sasl.h is not available. Run configure with --disable-memcached-sasl to disable this check ERROR: `/tmp/pear/temp/memcached/configure --with-libmemcached-dir=no’ failed [root@vps ~]# service httpd restart

Witch directory do I have to give it? And in the Section: OPTIONS=“-1 127.0.0.1”, I have delete the -1 and put only 127.0.0.1, are this right or do I replace your suggestion back?

Best Regards, Roger

Can we store session in Memcache in 1 central server and use the backend servers to access those sessions remotely ? It will help if we want to have a HA environment setup.

use this

pecl channel-update pecl.php.net

Hello, I love your blog. I’m studying memcached so I can implement on my websites. I have a basic question, when changed to memcached is there any modification I need to do on my php when I call a session or it should work as it is (at the basic level)? I’m just worried about bugging the entire thing once I install memcached. I know I’ll have to change how the session is initialized to share between my servers, I’m just wondering on the basic level as it is. Thanks for your help!

I got error 500 server error for my websites after installation on my vps . ı got php time out in my logs when i set sessions to be handled by memcached as explained here . Ive got centos6.5 php5.3.3 interworx panel

Always get fatal error class memcached not found ls /usr/lib/php/modules curl.so intl.so mysql.so posix.so sysvshm.so xsl.so dom.so json.so pdo_mysql.so soap.so wddx.so zip.so fileinfo.so mcrypt.so pdo.so sqlite3.so xmlreader.so gd.so memcached.so pdo_sqlite.so sysvmsg.so xmlrpc.so imap.so mysqli.so phar.so sysvsem.so xmlwriter.so memcached.so installed here, but it was white, instead running green.

ps aux | grep memcache 498 11476 0.0 0.0 56272 824 ? Ssl 01:59 0:00 memcached -d -p 11211 -u memcached -m 64 -c 1024 -P /var/run/memcached/memcached.pid -l 127.0.0.1 root 13887 0.0 0.0 4352 736 pts/1 S+ 02:17 0:00 grep memcache

i have add into /etc/php.ini extension=memcached.so either full path

php -v PHP Warning: PHP Startup: Unable to load dynamic library ‘/usr/lib/php/modules/memcached.so’ - /usr/lib/php/modules/memcached.so: undefined symbol: php_json_encode in Unknown on line 0

Warning: PHP Startup: Unable to load dynamic library ‘/usr/lib/php/modules/memcached.so’ - /usr/lib/php/modules/memcached.so: undefined symbol: php_json_encode in Unknown on line 0

if i disabled extension into php.ini either into memcached.ini, still no progress succeded.

All prequisites installation being correctly too, searching all over the web, have no answer for this class not found. yum -y groupinstall “Development Tools” yum -y install zlib-devel libmemcached-devel memcached-devel php-devel php-pear php-pecl-memcached

Dont know what im missing. Can anyone share me how to solve this issue :(.

Sorry i attached this long installation, hopefully useful

Libraries have been installed in: /var/tmp/pear-build-rootsw1f2D/memcached-1.0.0/modules If you ever happen to want to link against installed libraries in a given directory, LIBDIR, you must either use libtool, and specify the full pathname of the library, or use the `-LLIBDIR’ flag during linking and do at least one of the following:

  • add LIBDIR to the `LD_LIBRARY_PATH’ environment variable during execution
  • add LIBDIR to the `LD_RUN_PATH’ environment variable during linking
  • use the `-Wl,-rpath -Wl,LIBDIR’ linker flag
  • have your system administrator add LIBDIR to `/etc/ld.so.conf’

See any operating system documentation about shared libraries for more information, such as the ld(1) and ld.so(8) manual pages.

Build complete. Don’t forget to run ‘make test’.

running: make INSTALL_ROOT=“/var/tmp/pear-build-rootsw1f2D/install-memcached-1.0 .0” install Installing shared extensions: /var/tmp/pear-build-rootsw1f2D/install-memcach ed-1.0.0/usr/lib/php/modules/ running: find “/var/tmp/pear-build-rootsw1f2D/install-memcached-1.0.0” | xargs l s -dils 919062 4 drwxr-xr-x 3 root root 4096 Nov 30 02:07 /var/tmp/pear-build-rootsw 1f2D/install-memcached-1.0.0 919083 4 drwxr-xr-x 3 root root 4096 Nov 30 02:07 /var/tmp/pear-build-rootsw 1f2D/install-memcached-1.0.0/usr 919084 4 drwxr-xr-x 3 root root 4096 Nov 30 02:07 /var/tmp/pear-build-rootsw 1f2D/install-memcached-1.0.0/usr/lib 919085 4 drwxr-xr-x 3 root root 4096 Nov 30 02:07 /var/tmp/pear-build-rootsw 1f2D/install-memcached-1.0.0/usr/lib/php 919086 4 drwxr-xr-x 2 root root 4096 Nov 30 02:07 /var/tmp/pear-build-rootsw 1f2D/install-memcached-1.0.0/usr/lib/php/modules 919082 128 -rwxr-xr-x 1 root root 128994 Nov 30 02:07 /var/tmp/pear-build-rootsw 1f2D/install-memcached-1.0.0/usr/lib/php/modules/memcached.so

Build process completed successfully Installing ‘/usr/lib/php/modules/memcached.so’ install ok: channel://pecl.php.net/memcached-1.0.0 configuration option “php_ini” is not set to php.ini location You should add “extension=memcached.so” to php.ini

got this error after finishing memcached install

PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib64/php/modules/memcached.so' - /usr/lib64/php/modules/memcached.so: undefined symbol: php_msgpack_serialize in Unknown on line 0
/etc/php.d/z-memcached.ini

This comment has been deleted