Beyond building the most capable and appealing website possible, one of your highest priorities should be ensuring blazing fast load times. Not only will a highly responsive website increase visitor retention, but it will also positively affect your search engine results.
You probably know one of the easiest ways to improve performance is by caching all or parts of a page. But what might not be so obvious is exactly how this is accomplished. As it happens, a great solution called Memcached makes it trivial to incorporate caching into your website with great effect. In fact, relied upon by some of the largest websites in the world, among them Facebook, Twitter, Zynga, and YouTube, Memcached has essentially become the de facto website caching solution!
An open source project, Memcached's great advantages are available to any developer with a need for speed. With dozens of APIs available for all of the most popular Web development languages, PHP included, chances are the integration process is easier than you think.

Installing the PHP Memcached Extension

To begin, you'll need to install Memcached, subsequently starting the Memcached daemon. By default the daemon will run on port 11211. Be sure to write that number down as we'll return to it later. If you're running a Linux/Unix variant, then Memcached is almost certainly available via your respective package manager. On Ubuntu I installed it like so:
$ sudo apt-get install memcached
Processing triggers for man-db ...
Setting up memcached (1.4.5-1ubuntu2) ...
Starting memcached: memcached.
If you're running an alternative operating system, notably Windows, consult the Memcached website for documentation and other notes.
Next up, you'll want to obtain one of PHP's Memcached APIs. You'll often find two PHP-specific Memcached extensions referenced within documentation and other tutorials, notably PECL/memcache and PECL/memcached. I suggest using the latter for a variety of reasons, which have already been covered in some detail elsewhere.
After installing the libMemcached library, you can install the aforementioned memcached extension via PECL:
$ pear install pecl/memcached
Alternatively everything may be conveniently bundled within your operating system's package manager. For instance on Ubuntu installing the memcached extension and library is as simple as this:
$ sudo apt-get install php5-memcached
With Memcached and PHP's memcached extension installed, you're ready to begin caching!

Caching Your Data with PHP Memcached

Memcached uses a distributed approach to storing data in RAM using a key/value store, making for ridiculously fast data caching. You're free to begin caching data on the same Web server responsible for powering your website, and then add additional caching servers as demand increases. We'll focus on the former task for this article, however I suggest reading through the awesome Memcached FAQ to learn more about scaling possibilities.
The key/value store is quite flexible, allowing you to store simple integers, strings, and even the results of an entire database query. The latter capability is particularly advantageous, so let's consider an example based upon an online store which allows users to sort available games according to price. The following script will query a table named games for the name of all games associated with a price less than $29.99:

  // Connect to the MySQL server
  $db = new mysqli("localhost", "root", "jason", "test");

  $price = filter_var(29.99, FILTER_SANITIZE_NUMBER_FLOAT);

  $result = $d-->query("SELECT DISTINCT name FROM games WHERE price < {$price} ORDER BY name");

  while ($row = $result->fetch_assoc()){
", $row['name']); } ?>
The user might be provided with a simple drop-down menu containing a list of different price filters, meaning the same set of filters (say, $9.99, $19.99, $29.99, and $39.99) would be repeatedly used to query the database. It makes sense to cache such repetitive queries, associating their results with a key which can subsequently be used to retrieve the results in lieu of actually querying the database. I'll present the example in its entirety, followed by a review of crucial lines.
01 <?php
03  $m = new Memcached();
04  $-->addServer('', 11211);
06  $price = filter_var(29.99, FILTER_SANITIZE_NUMBER_FLOAT);
07  $price = 29.99;
09  $query = "SELECT DISTINCT name, publisher FROM games WHERE price < {$price} ORDER BY name";
11  $cacheKey = md5($query);
13  if (!($games = $m->get($cacheKey))) {
15    // Connect to the MySQL server
16    $db = new mysqli("localhost", "root", "jason", "test");
18    $price = filter_var(29.99, FILTER_SANITIZE_NUMBER_FLOAT);
19    $price = 29.99;
21    $result = $db->query($query);
23    $games = array();
25    while ($row = $result->fetch_assoc()){
26      printf("%s - %s
", $row['name'], $row['publisher']); 27 $games[] = array('name' => $row['name'], 'publisher' => $row['publisher']); 28 } 29 30 $m->set($cacheKey, $games); 31 32 } else { 33 34 foreach ($games AS $game){ 35 printf("%s - %s
", $game['name'], $game['publisher']); 36 37 } 38 39 } 40 41 ?>
Let's review the code:


This tutorial barely scratches the surface in terms of Memcached's capabilities. You can set keys in association with an expiration time, delete keys, append new values to keys, retrieve cache-related statistics, and much, much more. Be sure to check out PHP's Memcached documentation for all the details!

About the Author

Jason Gilmore is founder of the publishing, training, and consulting firm He is the author of several popular books "Easy PHP Websites with the Zend Framework", "Easy PayPal with PHP", and "Beginning PHP and MySQL, Fourth Edition". Follow him on Twitter at @wjgilmore.