Memcached tutorial

Memcached is a high performance object caching system for php. It’s a server based, so all your php codes can share the same data.

If you confused about memcached and memcache, shortly, both of them are clients for memcached server and memcached extension has more features than memcache.

I supposed you already installed php, then type below commands to install memcached:

apt-get update
apt-get install php5-memcached memcached

Check whether memchached is working or not in the any php page;

echo phpinfo();

Add at the end of php.ini file if not working. php.ini file location depends on linux distribution. You can find the location by typing below command.
locate php.ini

/etc/php5/apache2/php.ini is the right one for my ubuntu system.

You can check whether memchached is running or not;
ps aux | grep memcached
/usr/bin/memcached -m 64 -p 11211 -u memcache -l

Those memcached parameters come from the file located at /etc/memcached.conf . Let’s change memory 64mb to 1GB. To do this, change -m parameter to 1GB in memcached.conf file. Then restart memcached service.
service memcached restart
ps aux|grep memcached

/usr/bin/memcached -m 1GB -p 11211 -u memcache -l

Memcached usage is pretty simple, look below example;

if (class_exists(‘Memcache’)) {
$meminstance = new Memcache();
} else {
$meminstance = new Memcached();
$meminstance->addServer(“”, 55555);
$key = “ip-“.$_SERVER[‘REMOTE_ADDR’];
$result = $meminstance->get($key);
if ($result) {
$meminstance->set($key, $result+1);
} else {
$meminstance->set($key, 1);
$result = 1;
echo $result;

Change with your server ip and 55555 is your server port where memcached running. Above example will show viewing count for every ip.