Setting up and using PHP Memcache

What is Memcache? Memcache is an object-oriented mapping that is used to speed up dynamic database-drive applications by storing data in key-value pairs in RAM. In this blog, I will go through steps involved in setting up Memcache on a machine running Ubuntu and running a simple PHP program with Memcache.

For installing software, I will use Synaptic Package Manager.

Installing Memcache

  • Memcache is a PECL extension , so first, install PEAR. Go to Synaptic, find php-pear, and install it.
  • Next, install PHP development package.  Open Synaptic, find php-dev, and install it.
  • Build memcache module by running the following command:

$ pecl install memcache

  • You will see several lines of text run on the console. When done, you should see a success message and instruction telling you to add a line to your php.ini file. So, add the following line to your php.ini file:

  • Next, we need to install memcached so that we can fire up the memcache process. Open Synaptic Package Manager, and install memcached.
  • Start memcached process by running the following command on a terminal:

$ memcached -d -m 1024 -u root -l -p 11211

  • Now we’re ready to create a php program to test Memcache.

Writing a PHP program using Memcache

Below is a sample program that demonstrates how Memcached works:

$memcache = new Memcache;
$memcache->connect('', 11211) or 
die("Couldn't connect to memcache");

function getCache($key){
	global $memcache;
	return ($memcache) ? $memcache->get($key) : false;

function setCache($key, $object, $timeout = 60){
	global $memcache;
	return ($memcache) ? $memcache->set($key,
 $object, MEMCACHE_COMPRESSED, $timeout) : false;

$connection = mysql_connect('localhost', 'root', 'foobar')
 or die("can't connect to mysql");
mysql_select_db('test', $connection);

// test query
$key = md5("SELECT * FROM testtable WHERE id=2");
$get_result = getCache($key);

	echo $get_result['name'];
	echo $get_result['id'];
	echo "Data pulled from cache";
	$sql = 	"SELECT * FROM testtable WHERE id=2";
	$result = mysql_query($sql);
	$row = mysql_fetch_array($result);
	setCache($key, $row, 20);
	echo "Data pulled from database";

It is assumed that the table used exists. If all goes well, you will see that the data is pulled from database initially, and from memcached afterwards.

That’s it for now. Till next time, Goodbye.