Go4Expert

Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   Using Memcached in PHP (http://www.go4expert.com/articles/using-memcached-php-t28620/)

pradeep 23Jun2012 13:57

Using Memcached in PHP
 
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 Faster Webapps With Memcached.

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 http://pecl.php.net/package/memcached 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:

Code:

sudo apt-get install php5-memcached


Usage



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

Code: PHP

$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
$memc->addServer("localhost", 11211);

// set a value
$memc->set("name", "Pradeep");

// get the value
print $memc->get("name");


That was a very basic example, next let us look at more advanced usage:

Code: PHP

$memc = new Memcached();

$memc->addServer("10.20.1.2", 11211);
$memc->addServer("10.20.1.3", 11211);

// set a value & specify the data to expire in 5 mins
$memc->set("name", "Pradeep", 5 * 60);

// replace the value of the existing key, but not modifying the expiry time
$memc->replace("name", "Anjali");

// 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($data, time() + 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:

Code:

session.save_handler = "memcached"
session.save_path = "hostname:port"


The session key names are prefixed with memc.sess.key.


All times are GMT +5.5. The time now is 21:43.