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’m 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 extension=memcache.so 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
/etc/php5/cli/php.ini
/usr/share/php5/php.ini-development
/usr/share/php5/php.ini-production
/usr/share/php5/php.ini-production.cli

/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 127.0.0.1

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 127.0.0.1

Memcached usage is pretty simple, look below example;

if (class_exists(‘Memcache’)) {
$meminstance = new Memcache();
} else {
$meminstance = new Memcached();
}
$meminstance->addServer(“1.2.3.4”, 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 1.2.3.4 with your server ip and 55555 is your server port where memcached running. Above example will show viewing count for every ip.