Using Memcached with PHP in Linux

Written By: Ojameruaye Etaoghene Chimaobi

Using Memcached with PHP in Linux

Memcached is an object caching framework. It is essentially used to cached database querie, thereby reducing the the requests made on the database. It reduces the response time of your webapps. 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.

Installation and Usage Guide.

Installing Memcached on linux is pretty simple and straight forward. We would go through the steps one after the other:

Step 1: Installing Memcached.

First, make sure that your local package index is updated using the following command:

$ sudo apt update

Secondly, install the official package as follows:

$ sudo apt install memcached

You can also install libmemcached-tools, which is a package that contains various tools that you can use to examine, test, and manage your Memcached server. Add the package to your server with the following command:

$ sudo apt install libmemcached-tools

Memcached should now be installed as a service on your server, along with tools that will allow you to test its connectivity.

You can confirm if it is installed by using the command:

$ memcached --version

or you can use:

$ ps aux | grep memcached

Step 2: Installing PHP Memcached extensions.

To use Memcached with PHP you’ll have to install the PHP Memcached extension, and you can do by using the following command:

$ sudo apt-get install -y php-memcached

or you can use:

$ sudo apt install php-memcached

Then at this point the PHP extension is installed, and you can check it in you phpinfo() by running the following PHP codes in your index.php:

<?php

phpinfo();

?>

Now visit your site and scroll down to find Memcached.

Congratulations! You have succefully installed Memcached, it’s time to use it and see it in action.

Step 3: Using Memcached with PHP

To use memcached, you’ll have to start the memcached server, then instatiate the Memcached object, then add the server to use (you can use multiple servers), and then you can set the key and the value of the data you want to cache and you can also get them.

You can start memcached by running the following command:

$ sudo systemctl start memcached

Now you can run the following PHP script:

<?php

ini_set("display_errors", "on");

$memtest = new Memcached();

$memtest->addServer("127.0.0.1", 11211);

$memtest->set("test", "This is just for testing, and it's working. Congratulations!");

$result = $memtest->get("test");

if ($result) {

echo $result;

}else{

echo "There was an error";

}

?>

Now go to your site and see the result.

Congratulations!

要查看或添加评论,请登录

Cyclobold Tech的更多文章

社区洞察

其他会员也浏览了