Installing memcached on CentOS/cPanel

memcached a (distributed) memory object caching system vital if your running a HA Linux* setup or a web farm. Or even if you need fast as **** caching for an application.

Consider it extra memory for your server, so you can cache more, for example large arrays, SQL queries and other stuff!

* Actually I’ve discovered there are memcached extensions for Java, C & .NET. Wow, it just grew up!

The server I was using when I wrote this was a 32-bit machine running CentOS version 5.x. So my particular server was:

http://apt.sw.be/redhat/el5/en/i386/rpmforge/RPMS/rpmforge-release-0.3.6-1.el5.rf.i386.rpm

To install a new RPM server, we can just use the rpm command. Note that you must find the RPM server string that matches your architecture and software. Do not use the URL unless you have a 32-bit machine running CentOS 5.x, instead get the server that’s appropriate from http://dag.wieers.com/rpm/FAQ.php#B2.

$ rpm -Uhv http://apt.sw.be/redhat/el5/en/i386/rpmforge/RPMS/rpmforge-release-0.3.6-1.el5.rf.i386.rpm

Now we can simply use yum (or apt) to install Memcached:

$ yum install memcached

Afterwards you can confirm memcached is up and running by calling it.

$ memcached -h
memcached 1.2.6

Install the Memcache PECL Extension

Even though memcached is happily running on the server, it’s not accessible from PHP without the PECL extension. Fortunately this is a very easy process, just use the pecl command.

$ pecl install memcache

Then add the memcache extension to your php.ini file, usually at /etc/php.ini.

extension=memcache.so

And finally restart Apache so that it will pick up the new extension:

$ /etc/init.d/apache2 restart
Now you can configure you memcache compatible software. Good luck!
Here’s a PHP example;
<?php
 
$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
 
$version = $memcache->getVersion();
echo "Server's version: ".$version."<br/>\n";
 
$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;
 
$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";
 
$get_result = $memcache->get('key');
echo "Data from the cache:<br/>\n";
 
var_dump($get_result);
 
?>

Author: Kieran Barnes

Kieran is a PHP developer with 15 years commercial experience. Specialist in WordPress, CakePHP, CubeCart and all things PHP.

One thought on “Installing memcached on CentOS/cPanel”

  1. This web page can be a stroll-through for all of the information you wished about this and didn’t know who to ask. Glimpse right here, and you’ll undoubtedly uncover it.

Leave a Reply

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