Share icon

Memcache is very popular open source caching tool use in nowdays, this article is related to how we can use the memcache with PHP, So start

First of all you need to install memcache on your server, you can use this link or other according to your operating system

after installation follow below steps to make it work with php

1) Install php-memcached extension, use following command for linux 

sudo apt-get install -y php-memcached

2) restart the apache and check php information using phpinfo()

<?php
phpinfo();
?>

you will be able to see something like this 

memcache

3) Now create a simple php script to check how it works

<?php

try

{
    $memcached = new Memcached();
    $memcached->addServer("127.0.0.1", 11211); 
    $response = $memcached->get("key_cache");
 
    if($response==true) 
    {
      echo "Result coming from caching";
      echo $response;
    } 

    else

    {
    echo "Cache is not created yet, reload again to see changes";
    $memcached->set("key_cache", "Hooray! Memcache is working now ...") ;
    }
}
catch (exception $e)
{
echo $e->getMessage();
}
?>

4) Open file it web browser first time you will se following result

before cache

Reload the page again, now caching is done and result will come form cache

after cache

This will shows caching is working

If you get errors comment below

Thanks

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.