How to use memcached with PHP ?


Hello Guys, Today I would like to share with you most widely used Memcached caching with PHP. My last article was about "How to install memcached in WAMP /Windows." Today I will to show you how to use memcached with PHP. You may be wondering what I am talking about, "What is memcached and how it is works?" Here is the solution.

What is Memcached ?

Memcache is basically high performance distributed memory object caching. Simply to say it is allowing us to store datas locally into the web page itself in a "temporary cache". So each and every time you do not have to run database query and get datas from database. Instead of going to database to get data you can fetch from memcache if exists. This technique allow you to build most optimized application.

There are few functions which we are using mainly in memcache. Let us see what are they,

i. Get() – get the value for a specified key

ii. Set() – sets a given key with a given value

iii. Add() – add values to the cache if it is not exists

iv. Replace() – sets datas into cache if key already exists

v. Flush() – removes all keys and cached data

Who uses Memcache ?

Facebook uses memcache

Now a days, lots of well known websites like Facebook, Twitter, Digg, Youtube are using Memcache. Currently Facebook is the biggest Users of Memcache.

How to use Memcached With PHP?

So hope you all people know how to install memcache in your local server (Server) as I have shown you how to install memcache in WAMP in my previous post. So now let us see how to work with memcache.

Step 1:

First create MemCache.php in your local server. Now paste below code into the file.

class MemCache {

public $expireTime = 60; // Set the expire time
private $isEnabled = false; /* Memcache Isenabled */
private $objCache = null;   

    public function __construct() {

        if (class_exists('Memcache')) {

            $this-> objCache = new Memcache();
            if(!$this->objCache->connect('localhost', 11211)) {
                  $this->objCache->connect('localhost', 11211);
                    $this->isEnabled = true;
  public function getDetails() {
             //Set the key and check the cache
      $cacheKey = md5("SELECT * from user_info where user_id='121'");
      $cacheResult = $this-> objCache ->get($cacheKey);

      if ($cacheResult) {
          echo $cacheResult['username'];
          echo $cacheResult['email_id'];
      } else {
          echo $data[‘username’]." -".$data[‘password’] ."-".$data[‘email_id’]." 
"; } } public function setData() { $query="SELECT * from user_info where user_id='121'"; $result = mysql_query($query); $row = mysql_fetch_array($result); //Use MEMCACHE_COMPRESSED to store the item compressed (uses zlib). $data = $this->objCache->set($cacheKey, $row, 0, $this->expireTime); // Store the result in cache for 60 seconds return $data; } // delete data from cache server function deleteData($cacheKey) { $success_val = $this-> objCache ->delete($cacheKey); return $success_val; } }

Step 2:

Create another file called connection.php and paste below code into it.

$hostname = "localhost";
$user = "root";
$password = " ";
$database = "social_network";

$conn = mysql_connect($hostname, $user, $password) 
or die("Ooppsss!! Something went wrong");
mysql_select_db($database, $conn) or die(: Ooppsss !! Could not able to connect database");

That's all we are done. You can include the connection.php top of the page and before using MemCache.php file

This is a simple example how cache works. Hope this post helps you to optimize your web application. Please do share and post your comments here. And If you would like me to write anything else then please contact me. All the best. Have a good day.


  1. Are you aware that memcache and memcached are different?

    1. Yeah there is Some differences between this two. Anyways If you have much idea about it please do share.

      It may help others too.

      With Regards,

  2. Its no the same memcache that memcached, Why this title is Memcached and explain how to implement memcache

  3. Excellent it helps me lot...


Follow Us On Facebook Open Source Web Developers by Appsntech facebook group Twitter Open Source Web Developers by Appsntech twitter group Google+ Open Source Web Developers by Appsntech Google group Linkedin Open Source Web Developers by Appsntech, LinkedIn group
Copyright @2011-2015 All rights reserved. Powered By- Sanjoy Dey Productions