How Do You Install Memcached on an Ubuntu Server?

Problem scenario
You want to try out Memcached.  How do you install memcached and php-memcached to test it?

Solution
(These directions were based on ServerMom.org directions.)

1.  Run these commands:

sudo apt-get -y update
sudo apt -y install memcached php-memcached php7.0 apache2
  # apache2 is not necessary but useful for testing purposes

2.  Create this file:
sudo vi /var/www/html/info.php # add the three lines below

<?php
phpinfo();
?>

3.  Run these commands:
sudo service memcached restart
sudo service php7.0-fpm restart

4.  In /var/www/html/ create a file called contint.php.  Use this as the content:

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

$result = $mem->get("blah");

if ($result) {
    echo $result;
} else {
    echo "This is the FIRST time that you downloaded this page!";
    $mem->set("This is not the first time you have downloaded this page.  This is held in memcached") or die("Couldn't save anything to memcached...");
}
?>

5.  Test it out. Browse to the web page with a web browser (e.g., http://x.x.x.x/contint.php).  Then click refresh.  You should see the first message followed by the second message.

If you want to purchase a book on Memcached, click here.

Leave a comment

Your email address will not be published. Required fields are marked *