Installing memcache for PHP 5 on Linux CentOS

Posted on Mar 20, 2009 in PHP |

This has been tested on CentOS but should work on most distros:

Memcache is a caching mechanism for PHP which speeds up access to data by storing it in the RAM. Memcache runs as a server in a similar fashion to a database, except that data is not persistent in the long term. The great thing about Memcache is you don’t need to recompile php. Here’s some instructions on how to install and set it up.

Firstly install the memcache program:

yum install php-pecl-memcache

Next ensure that it is started on system startup/reboot

chkconfig memcached on

Now start up the daemon

/etc/init.d/memcached start

That should be all! Check if it’s working by running this test script:

connect('localhost', 11211) or die ("Could not connect");
echo "Server's version: {$memcache->getVersion()}
"; //Create and save a test class $tmp = new stdClass; $tmp->string_attribute = 'testing'; $tmp->string_attribute = 123; $memcache->set('key', $tmp, false, 10) or die ("Failed to save temporary object at memcache server"); //Access the memcache data echo "Data from the cache:
n"; print_r($memcache->get('key')); ?>

If you find you’re getting errors like this:

Warning: Memcache::connect() [memcache.connect]: Can't connect to localhost:11211, Connection refused (111)

or also just “Could not connect”, there’s a good chance that either the memcache daemon isn’t working or that the server is not running on the right port.

To check that it’s running on the right port, run this:

netstat | grep 11211


ps -A | grep memcached

These should both output something confirming the it’s running.