Official website for Linux User & Developer

Speed up your PHP applications with memcached

by Kieron Howard

How to reduce load on your database by minimising the number of database requests you need to make

Step 13

Run PEAR install

To run the install, enter ‘php go-pear.php’, making sure that you are in the same directory that you just downloaded it to. Follow the on-screen instructions. You can then check it’s all working properly by using ‘pear’ in the terminal.

Step 14

Install memcache PHP

To install the PHP memcache extension, just enter:

sudo pecl install memcache

This will download and install the necessary PHP extension. While it’s possible to use memcached without it, being able to make static calls can really speed things up.

Edit PHP.ini

Step 15

Edit PHP.ini

You’ll need to add a line to your php.ini file that tells PHP to load in the memcache extension when it first launches. To do that, open your php.ini file in your favourite text editor and enter:

Then restart Apache with:

service httpd restart

Once that’s done, you can check that it’s loaded by running:

php -i|grep’memcache

There you should see:

memcache => support enabled

You are now ready to start using the service in your PHP apps.

Step 16

Start server

Now we can start our server, and add items to it using static PHP methods.
Create a new PHP file and add:

$memcache = new Memcache(); $memcache->connect(‘’ , 11211) or die(‘failed to connect to server’);

This creates a new instance, running on the 11211 port, and then we connect to the server.

Step 17

Add values

Next let’s add some data to the cache. First we need a key which we can use to identify the data when we are ready to retrieve:

$key = md5(‘myKey);

Then we need some data. For now we will just make a test string:

$data = ‘My Test Data’;

Step 18

Cache data

Now we can store the data on our server using the ‘set’ method. We then add our key, data, whether or not to compress the data, and the time to live for the cache. In this case we are using 20 seconds:

$memcache->set($key , $data , TRUE ,20 );

Step 19

Retrieve data

To get data back out, we use the ‘get’ method, like so:

$retrievedData = $memcache- >get($key);

Obviously we will need to have done this within the 20 seconds of the cache’s life.

Step 20

Using memcache with a DB

On its own this isn’t terribly useful, so let’s use it to cache a common database query such as returning a user’s avatar:

$key = md5(‘SELECT * FROM mydatabase
WHERE useravatarid = 1’);
$retrievedData = $memcache
$avatar =

Step 21


Then, if there is nothing matching the key in the memcache server’s memory, we will run our query as normal, and then cache it.

$query = ‘SELECT * FROM mydatabase WHERE useravatarid =1’;
$avatars = mysql_query($query); $userAvatar = mysql_fetch_ array($avatars); $memcache->set($key, $userAvatar , FALSE , 1024);

Step 22

Get server status

To get info on the state of your server, you can use the getServerStatus method:



This will return a 0 if the server has exited.

For more information you can use:


…where the type can be :reset, malloc, maps, cachedump, slabs, items or sizes.

Step 23

Replacing a cached value

Sometimes it might be required to replace a previously entered value in the cache. To do that, use the replace method:

$memcache->replace($key, $myData, false, 60);

If the key is not found, replace will return FALSE. You can use this within a function to test for previously cached data.

Flush the cache

Step 24

Flush the cache

To remove all entries from the cache, just use the flush method. This could be run when a user logs out, to free up server memory for another user for instance.


As you can see, memcached is a very easy-to- use tool, but can really speed up apps with high database input/output.

Pages: 1 2
  • Tell a Friend
  • Follow our Twitter to find out about all the latest Linux news, reviews, previews, interviews, features and a whole more.
    • Pingback: Links 29/11/2012: Dell Sells GNU/Linux Gear at Lower Cost Than Windows, Fedora 18 Reaches Beta | Techrights()

    • If you are using wordpress then you can directly use the below plugin

    • I visited several sites however the audio quality for audio songs current at this web page is in fact superb.

    • I am regular reader, how are you everybody?
      This piece of writing posted at this web site is genuinely good.

      Visit my website at laminate flooring kilmarnock

    • hello there and thank you for your info – I’ve certainly picked up something new from right here. I did however expertise several technical points using this site, since I experienced to reload the web site a lot of times previous to I could get it to load correctly. I had been wondering if your hosting is OK? Not that I am complaining, but sluggish loading instances times will often affect your placement in google and could damage your quality score if ads and marketing with Adwords. Anyway I’m adding this RSS
      to my email and could look out for much more of your respective intriguing content.
      Make sure you update this again soon.Visit my website at bike valet

    • I was suggested this website by my cousin.
      I am not sure whether this post is written by him
      as nobody else know such detailed about my problem.
      You’re amazing! Thanks!Visit my website at bike expo

    • Hey this is somewhat of off topic but I was wanting to
      know if blogs use WYSIWYG editors or if you have
      to manually code with HTML. I’m starting a blog soon but have no coding knowledge so I wanted to get guidance from someone with experience. Any help would be greatly appreciated!Visit my website at obrusy euromat

    • Superb ! Great tutorial. I have learnt this tutorial . It’s very useful selection . This tutorial will make a good helper for php programmer .Really it will very useful for all users.

      Thanks for sharing great tutorial . Keep it up .