Switch to full style
:read: Start PHP with us. Includes topics to help you in php
Post a reply

using cache extension with php

Mon Jul 23, 2012 10:10 pm

In order to have higher performance php web application you can use caching modules, in this article we talk about open source caching module named “Memcached” with php. We will discuss how to install memcached in PHP.

After downloading the memcached package, you can run following command:
sudo apt-get install php5-memcached
We assume that you are using PHP5; when dealing with memcached extension you will be dealing with user friendly OOP interface, check the code below:
Code:
$memoryCacheObj = new Memcached();

// assuming you have a memcached daemon running in the local system
// port defaults to 11211

$ memoryCacheObj ->addServer("localhost", 11211);

// cache value
$ memoryCacheObj ->set("username", "codemiles");

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

Here is another example with more usage :
Code:

$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 7 minutes
$memc->set("username", "codemiles", 7 * 60);

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

// append data to an existing value
print $memc->append("username","as");

 

// set multi-able elements 
$data = array(
    'username' => 'codemiles',
    'city' => 'newyork',
    'age' => '33');

// set the multi elements array and set to expire 7 minutes from now
$memc->setMulti($data, time() + 7 * 60);

// get multiple elements
$dataCached = $memc->getMulti(array('username', 'city', 'age')); 

You can also save the session data using Memcached solution and this will make the handling faster, you can change it from php.ini:
Code:
Code:
session.save_handler = "memcached"
session.save_path = "hostname:port"


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

You can download it from here :
Code:
http://pecl.php.net/package/memcached




Post a reply
  Related Posts  to : using cache extension with php
 Solution to AJax Cache problem with Internet Explorer     -  
 Get filename full path,extension and filename     -