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.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

Using Memcached with PHP

Updated on December 1, 2021

6 Min Read
php memcached

Memcached is an object caching framework. It is essentially used to cache the database queries, making a difference in dynamic websites like Drupal and WordPress to serve pages quicker. It can moreover significantly decrease resource use on an active web server by reducing calls to the database.

Memcached is a distributed memory caching system. It speeds up websites having large dynamic databases by storing database objects 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.

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

In Layman’s Terms

Let’s conjure up an analogy. Suppose you are a manager of a DVD store that 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 storekeeper. Now, these assigned keys can be circulated among your customers and whenever these customers request that particular key, your storekeeper 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 storekeeper. 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 moving 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 decreases 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.

Get Ready for Core Web Vitals Update

Ebook to Speed Up Your Website Before You Start Losing Traffic.

Thank You

Your list is on it’s Way to Your Inbox.

How to setup Memcached?

To enable the PHP Memcache extensions, you need to build PHP utilizing –enable-Memcache option when building, and configure it from the source. On Debian-based dispersions, you can use the php-Memcache package. To set global runtime configuration choices, specify the configuration option values within your php.ini record.

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.

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.

    Step-1:

    •  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
<?php
phpinfo();
?>

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:

<?php
$mem_var = new Memcached();
$mem_var->addServer("127.0.0.1", 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 :'( ");
}
?>

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");
exit

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.

<?php
$memtest = new Memcached();
$memtest->addServer("127.0.0.1", 11211);
?>

Just like we did before

<?php
$memtest = new Memcached();
$memtest->addServer("127.0.0.1", 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 that 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.

<?php
$memtest = new Memcached();
$memtest->addServer("127.0.0.1", 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

Supercharged Managed PHP Hosting – Improve Your PHP App Speed by 300%

– What is the difference between Memcache and Memcached?

Both Memcache and Memcached have a fundamental difference, i.e., “while storing value. Memcache considers every value as string whereas Memcached stores its value’s original type.”

– How to Configuring Memcached PHP

  • Download Memcached.
  • Install Memcached, then run it on your computer.
  • Confirm either your PHP code is compiled with Memcached.
  • Stack the memcached extension from within PHP, and restart the web server.
  • Memcached should now be working.
Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahzeb Ahmed

Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways. He is growth ambitious and aims to learn & share information about PHP & Laravel Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]

×

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

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now