Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Using Memcached with PHP

April 7, 2016

5 Min Read
php memcached
Reading Time: 5 minutes

Memcached is a distributed memory caching system. It speeds up websites having large dynamic databasing by storing database object in Dynamic Memory to reduce the pressure on a server whenever an external data source requests a read. A memcached layer reduces the number of times database requests are made.

In Layman’s Terms

Let’s conjure up an analogy. Suppose you are a manager of a DVD store which has lots of movies and games with different genres like sci-fi, history and drama. You assign some keys to the movies that customers ask for a lot and paste them on a front counter for the ease of the store keeper. Now these assigned keys can be circulated among your customers and whenever these customers request that particular key, your store keeper doesn’t have to get into the details of the movies but just fetch them the DVDs. This will increase the response time of your store keeper. All the requests for which the keys are not found will be looked into in detail to find out which movies the customers are requesting.

The delivery process will be as rapid as the assignment of the keys. These keys act as speed buffer by passing all the details one has to look into for fetching movies.

These same things happen to the content your web page is serving. Memcached stores the values (v) with the key (k) and retrieves the values (v) with the key (k) without even parsing the database queries and stays away from all these hassles.

Why Memcached?

It increases the response time of your web pages, which in return enhances the overall customer’s experience. A better response time allows users to fetch data seamlessly.

How to setup Memcached?

If you are a Cloudways user, you don’t have to worry about all that hassle, it has all be done for you. Scroll down to learn how can you configure your PHP app with Memcached.

Host Your PHP Apps With Us For 10x Faster Performance

Don’t Let Your Customers Run Away With The Downtimes. Deploy With Us Today!

Configuring PHP app for Memcached:

Ok, so let’s start by ticking off the prerequisites checklist. Do not worry as its just a matter of few clicks:

  •  Make sure you have an active server on Cloudways. Click here to get access to your own cloud server.
  •  Make sure you have launched a PHP app. If not, then you can follow this guide to setup your PHP Stack with Cloudways.


    •  Make sure you have Memcached working, you can check it by typing the following command in terminal.
    $ps aux | grep memcached

MemCached with PHP

You can also try the following

	$netstat -ap | grep 11211
  •  Now that it’s working, let’s see our phpinfo() page to check the version of memcached we are using.
  •  Paste the following code in your index.php

Now visit your site and scroll down to find memcached. You will see something like this:

MemCached with PHP

Let’s play with our installed MemCached and see what we can do with it. We will be saving some Value (V) in our MemCached and will associate this Value with a Key (K). We will name our Key “Bilbo” and it will fetch us the Valued (“Ring”). Here is a small code:

$mem_var = new Memcached();
$mem_var->addServer("", 11211);
$response = $mem_var->get("Bilbo");
if ($response) {
&nbsp; &nbsp; echo $response;
} else {
&nbsp; &nbsp; echo "Adding Keys (K) for Values (V), You can then grab Value (V) for your Key (K) \m/ (-_-) \m/ ";
&nbsp; &nbsp; $mem_var->set("Bilbo", "Here s Your (Ring) Master stored in MemCached (^_^)") or die(" Keys Couldn't be Created : Bilbo Not Found :'( ");

Give Your PHP Applications Optimum Web Performance

Host Your PHP Apps With Us & See The Blazing Web Performance Yourself!

Every time we call the Bilbo, Bilbo will bring the Key for us. Save the Code in your Index.php and exit.

Now visit your app in a browser. You will see something like this:

MemCached with PHP

And now refresh:

MemCached with PHP

Now let’s get back to serious stuff :D, we will connect MySql without PHP code and will see how can we take benefit out of Memcached.

You might also like: How To Connect MySQL Database With PHP Websites

First, launch MySql with CLI. And create a Table as follows. Remember your MySql Credentials are provided in your server settings page.

$mysql -u <user_name> -p
mysql> <enter Password here>
Use <database name> CREATE TABLE sample_data (id int, name varchar(30));
INSERT INTO sample_data VALUES (1, "some_data");

We created a simple table. Let’s move on to the next step. Make a new PHP file. Name it memtest.php

And let’s get these codes inside it.

$memtest = new Memcached();
$memtest->addServer("", 11211);

Just like we did before

$memtest = new Memcached();
$memtest->addServer("", 11211);
mysql_connect("localhost", "<username>", "password") or die(mysql_error());
mysql_select_db("<username>") or die(mysql_error());

Next, we’ll make a simple query to get us the Value V from DB and will make a Key (K) that will be stored in Memcached.

We’ll then create a $querykey variable to store the key for Memcached to remember our value.

Let’s create a key by name “KEY” and then appending the md5 (a hashing method) checksum function. This will always generate a unique key which helps us manage the large data set. It also ensures that a matching query will produce the same key for subsequent requests.

Next, we will echo out the result and will see whether this was from memcached or a simple fetching.

$memtest = new Memcached();
$memtest->addServer("", 11211);
$conn = mysql_connect("localhost", "tzvsqktpzm", "XWwgPDZ52R") or die(mysql_error());
mysql_select_db("tzvsqktpzm") or die(mysql_error());
$query = "SELECT ID FROM sample_data WHERE name = 'some_data'";
$retval = mysql_query( $query, $conn );
$result = mysql_fetch_array($retval, MYSQL_ASSOC);
$querykey = "KEY" . md5($query);
$memtest->set($querykey, $result);
$result2 = $memtest->get($querykey);
if ($result2) {
print "<p>Data was: " . $result2['ID'] . "</p>";
print "<p>Caching success!</p><p>Retrieved data from memcached!</p>";

We will be caching for a few seconds now, you will have to change a bit depending on your usage. It’s just to see the quick results without restarting the memcached.

MemCached with PHP

Share your opinion in the comment section. COMMENT NOW

Share This Article

Launch PHP websites without the worry of Server Management.

Pre-Installed Optimized Stack with Git, Composer & SSH

Noor Ali

Noor Ali is an Associate Software Engineer at Cloudways. He loves to solve technical problems through programming and mathematics.

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

BFCM 2019