Using Memcached in PHP

Discussion in 'PHP' started by pradeep, Jun 23, 2012.

  1. pradeep

    pradeep Team Leader

    Apr 4, 2005
    Likes Received:
    Trophy Points:
    Kolkata, India
    Home Page:
    Memcached is a high-performance open-source caching solution, generally used to improve web application performance by avoiding round-trips to RDBMS, to know more about memcached read [THREAD=27372]Faster Webapps With Memcached[/THREAD].

    In this article we'll discuss about installing and using memcached in PHP. A PHP extension is available for working with memcached with requires the C libmemcached library to be present.

    Installing memcached PHP extension

    Download the latest release of PECL memcached PHP extension from and unpack it.

    Compile & install. Now, you can check the availability of the extension using phpinfo().

    If you are running Ubuntu variant or Debian & running PHP 5, just run the following to install the PHP extension:

    sudo apt-get install php5-memcached


    Memcached PHP extension provides an OOP interface, which is very easy, follow the code sample below to get an idea of the usage.

    $memc = new Memcached();

    // assuming you have a memcached daemon running in the local system
    // port defaults to 11211
    // you may add multiple servers, memcached will auto-distribute keys between them

    // set a value

    // get the value
    print $memc->get("name");
    That was a very basic example, next let us look at more advanced usage:

    $memc = new Memcached();


    // set a value & specify the data to expire in 5 mins

    // replace the value of the existing key, but not modifying the expiry time

    // append data to an existing value
    print $memc->append("name"," is cool!");

    // similaryly prepend
    print $memc->prepend("name","Dude ");

    // set mulitple items at once
    $data = array(
    'name.1' => 'Pradeep',
    'city.1' => 'Kolkata',
    'hobby.1.1' => 'Cycling',
    'hobby.1.2' => 'Photography'

    // set the multi key-value pairs, and set to exipre 10 mins from now
    $memc->setMulti($datatime() + 600);

    // similarly get multiple keys at once
    $get_data $memc->getMulti(array('name.1''hobby.1.1''hobby.1.3'));

    Using Memcached for Session

    You may store user session data in Memcached instead of regular file handler, which make sessions faster & independent of the server where the request lands (in case you have multiple servers under a load balancer). Here's what you need to do to use memcached for session.

    In php.ini set the following:

    session.save_handler = "memcached"
    session.save_path = "hostname:port"
    The session key names are prefixed with memc.sess.key.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice