Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg

PHP : Function Reference : Memcache Functions

Memcache Functions


Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

The Memcache module also provides a session handler (memcache).

More information about memcached can be found at »


This module uses functions of » zlib to support on-the-fly data compression. Zlib is required to install this module.

PHP 4.3.3 or newer is required to use the memcache extension.


This » PECL extension is not bundled with PHP. Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: »

In order to use these functions you must compile PHP with Memcache support by using the --enable-memcache[=DIR] option. You may optionally disable memcache session handler support by specifying --disable-memcache-session.

Windows users will enable php_memcache.dll inside of php.ini in order to use these functions. The DLL for this PECL extension may be downloaded from either the » PHP Downloads page or from »

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 170. Memcache Configuration Options

Name Default Changeable Changelog
memcache.allow_failover "1" PHP_INI_ALL Available since memcache 2.0.2.
memcache.max_failover_attempts "20" PHP_INI_ALL Available since memcache 2.1.0.
memcache.chunk_size "8192" PHP_INI_ALL Available since memcache 2.0.2.
memcache.default_port "11211" PHP_INI_ALL Available since memcache 2.0.2.
memcache.hash_strategy "standard" PHP_INI_ALL Available since memcache 2.2.0.
memcache.hash_function "crc32" PHP_INI_ALL Available since memcache 2.2.0.
session.save_handler "files" PHP_INI_ALL Supported since memcache 2.1.2
session.save_path "" PHP_INI_ALL Supported since memcache 2.1.2

For further details and definitions of the PHP_INI_* constants, see the Appendix I, php.ini directives.

Here's a short explanation of the configuration directives.

memcache.allow_failover boolean

Whether to transparently failover to other servers on errors.

memcache.max_failover_attempts integer

Defines how many servers to try when setting and getting data. Used only in conjunction with memcache.allow_failover.

memcache.chunk_size integer

Data will be transferred in chunks of this size, setting the value lower requires more network writes. Try increasing this value to 32768 if noticing otherwise inexplicable slowdowns.

memcache.default_port string

The default TCP port number to use when connecting to the memcached server if no other port is specified.

memcache.hash_strategy string

Controls which strategy to use when mapping keys to servers. Set this value to consistent to enable consistent hashing which allows servers to be added or removed from the pool without causing keys to be remapped. Setting this value to standard results in the old strategy being used.

memcache.hash_function string

Controls which hash function to apply when mapping keys to servers, crc32 uses the standard CRC32 hash while fnv uses FNV-1a.

session.save_handler string

Use memcache as a session handler by setting this value to memcache.

session.save_path string

Defines a comma separated of server urls to use for session storage, for example "tcp://host1:11211, tcp://host2:11211".

Each url may contain parameters which are applied to that server, they are the same as for the Memcache::addServer() method. For example "tcp://host1:11211?persistent=1&weight=1&timeout=1&retry_interval=15"

Resource Types

There is only one resource type used in memcache module - it's the link identifier for a cache server connection.

Predefined Constants

Table 171. Memcache Constants

Name Description
MEMCACHE_COMPRESSED (integer) Used to turn on-the-fly data compression on with Memcache::set(), Memcache::add() and Memcache::replace().
MEMCACHE_HAVE_SESSION (integer) 1 if this Memcache session handler is available, 0 otherwise.


Example 1305. memcache extension overview example

In this example, an object is being saved in the cache and then retrieved back. Object and other non-scalar types are serialized before saving, so it's impossible to store resources (i.e. connection identifiers and others) in the cache.


= new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");

$version = $memcache->getVersion();
"Server's version: ".$version."<br/>\n";

$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;

$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
"Store data in the cache (data will expire in 10 seconds)<br/>\n";

$get_result = $memcache->get('key');
"Data from the cache:<br/>\n";



Example 1306. Using memcache session handler


= "tcp://$host:$port?persistent=1&weight=2&timeout=2&retry_interval=10,  ,tcp://$host:$port  ";
ini_set('session.save_handler', 'memcache');
ini_set('session.save_path', $session_save_path);


Table of Contents

Memcache::add — Add an item to the server
Memcache::addServer — Add a memcached server to connection pool
Memcache::close — Close memcached server connection
Memcache::connect — Open memcached server connection
memcache_debug — Turn debug output on/off
Memcache::decrement — Decrement item's value
Memcache::delete — Delete item from the server
Memcache::flush — Flush all existing items at the server
Memcache::get — Retrieve item from the server
Memcache::getExtendedStats — Get statistics from all servers in pool
Memcache::getServerStatus — Returns server status
Memcache::getStats — Get statistics of the server
Memcache::getVersion — Return version of the server
Memcache::increment — Increment item's value
Memcache::pconnect — Open memcached server persistent connection
Memcache::replace — Replace value of the existing item
Memcache::set — Store data at the server
Memcache::setCompressThreshold — Enable automatic compression of large values
Memcache::setServerParams — Changes server parameters and status at runtime

Code Examples / Notes » ref.memcache


You can't call parent::__construct() in the constructor of your class if you are extending the memcache class. However, not running the constructor still initiates it and works fine.
// wrong
class a extends Memcache {
 function __construct($host, $port)
   $this->connect($host, $port);
class a extends Memcache {
 function __construct($host, $port)
   $this->connect($host, $port);
I am guessing this applies to all native/PECL classes.

roberto spadim

You can use tugela cache if you want disk and memory cache


When installing the memcache module for Apache/PHP with a non-standard location it seems like there is no way to define the location when configuring for build. You'll get an error complaining about being unable to find php_session.h. I modified configure to try the PREFIX location too and that seems to have worked fine.
   if test -f "${prefix}/include/php/ext/session/php_session.h"; then
   elif test -f "$abs_srcdir/include/php/ext/session/php_session.h"; then
   elif test -f "$abs_srcdir/ext/session/php_session.h"; then
   elif test -f "$phpincludedir/ext/session/php_session.h"; then


There is a tiny bug in the Aggregator class when using the flush() function. The reference to $connections should be $this->connections.
public function flush() {
 $result = false;
 for ($i = 0; $i < count($connections); $i++) {
   if ($this->connections[$i]->flush()) {
     $result = true;
 return $result;
public function flush() {
 $result = false;
 for ($i = 0; $i < count($this->connections); $i++) {
   if ($this->connections[$i]->flush()) {
     $result = true;
 return $result;

gregor j. rothfuss

The next version will have failover. It's been committed three weeks ago. Usage notes here:


Re. Installing the memcache extension:
I had all kinds of troubles getting it hooked up, because in all of the instructions I read I never got the last, most important step - you must have a php.ini and have in it ""
So, the steps:
First - ./configure with --enable-memcache. This should show in your phpinfo() at the top (even though nothing of the memcache extension works yet).
either pecl install memcache
download the source
tar -xzvf [thesourcetarball]
make install
Finally: Add to your php.ini. (If you don't have one, it should go in the root of where php is called ie., /usr/local/lib)
Call phpinfo() and you should see a memcache section.


one more "intelligent" cache aggregator: trunk/core/Cache/AggregateCache.class.php
can be used with several cache connectors - memcached, filesystem, etc.
(remove whitespace manually)

colin guthrie

I have noticed a bug/documentation error:
The above docs say the following about the session.save_path arguement:
"Each url may contain parameters which are applied to that server, they are the same as for the Memcache::addServer() method. "
addServer method's docs say:
   Point to the port where memcached is listening for connections. This parameter is optional and its default value is 11211. Set this parameter to 0 when using UNIX domain sockets. "
However when specifying the save_path, I have found that with PHP 5.2.3 and memcache 2.1.2 that the port is a *required* part of the string.
Hope that helps some people scratching their heads.


Hi there:
For run memcached in a windows box: (tested with latest php,apache and memcache in xp sp2)
a) download the php_memcache.dll it can be found in the pecl file.
b) put the dll in the extension folder (c:/php/extension for example). You cannot miss this folder because they are filled with php*.dll files.  In some cases the extension folder used is the system32, a non-standard way to put dll but still works.
c)configure the php.ini
; i put this like the latest extension
; i'm not sure about this but don't hurts..
memcache.allow_failover = 1
memcache.chunk_size =8192
memcache.default_port = 11211
d)This is important, memcached works with a EXTERNAL service. This service must be downloaded and installed prior to use the memcache.  I use:
e)Remember to install the service and to start the service memcached.exe -d install for install and run services.msc for start the memcached service (or restart the system).
f) check the firewall ports.
Finally restart the apache/iis and runs some test. At least in phpinfo must show some info about the memcache.
Final notes :The "awe" about memcache is not only can help for speed some process (or reduce the cpu use), also can be used like a global session for store a whole object also this "global session" is shared among all the users, like APPLICATION used in ASP.  So (for example) it's possible to do a user counter without needing of database or writing a file.


Here is a simple memcached aggregator class which distributes the cache among multiple cache servers.  If a server fails, the load is redistributed automatically.  It uses persistent connections.
The constructor takes an array of arrays, with each inner array representing a server, with a 'server' (string) attribute that is the IP addres or host name of the memcached server, and a 'port' (int) attribute that is the port number on which memcached is running on the server.
All of the existing memcached API functions are implemented except getStats() and getVersion(), which are server-specific.
class MemcachedAggregator {
   var $connections;
   public function __construct($servers) {
// Attempt to establish/retrieve persistent connections to all servers.
// If any of them fail, they just don't get put into our list of active
// connections.
$this->connections = array();
for ($i = 0, $n = count($servers); $i < $n; $i++) {
   $server = $servers[$i];
   $con = memcache_pconnect($server['host'], $server['port']);
   if (!($con == false)) {
$this->connections[] = $con;
   private function _getConForKey($key) {
$hashCode = 0;
for ($i = 0, $len = strlen($key); $i < $len; $i++) {
   $hashCode = (int)(($hashCode*33)+ord($key[$i])) & 0x7fffffff;
if (($ns = count($this->connections)) > 0) {
   return $this->connections[$hashCode%$ns];
return false;
   public function debug($on_off) {
$result = false;
for ($i = 0; $i < count($connections); $i++) {
   if ($this->connections[$i]->debug($on_off)) $result = true;
return $result;
   public function flush() {
$result = false;
for ($i = 0; $i < count($connections); $i++) {
   if ($this->connections[$i]->flush()) $result = true;
return $result;
/// The following are not implemented:
   public function get($key) {
if (is_array($key)) {
   $dest = array();
   foreach ($key as $subkey) {
$val = get($subkey);
if (!($val === false)) $dest[$subkey] = $val;
   return $dest;
} else {
   return $this->_getConForKey($key)->get($key);
   public function set($key, $var, $compress=0, $expire=0) {
return $this->_getConForKey($key)->set($key, $var, $compress, $expire);
   public function add($key, $var, $compress=0, $expire=0) {
return $this->_getConForKey($key)->add($key, $var, $compress, $expire);
   public function replace($key, $var, $compress=0, $expire=0) {
return $this->_getConForKey($key)->replace
   ($key, $var, $compress, $expire);
   public function delete($key, $timeout=0) {
return $this->_getConForKey($key)->delete($key, $timeout);
   public function increment($key, $value=1) {
return $this->_getConForKey($key)->increment($key, $value);
   public function decrement($key, $value=1) {
return $this->_getConForKey($key)->decrement($key, $value);


Here is a PHP4 backport of the above MemcacheAggregator class:
class MemcachedAggregator {
   var $connections;
   var $_servers;
   function MemcachedAggregator($servers) {
       $this->_servers = $servers;
       // Attempt to establish/retrieve persistent connections to all servers.
       // If any of them fail, they just don't get put into our list of active
       // connections.
       $this->connections = array();
       for ($i = 0, $n = count($servers); $i < $n; $i++) {
           $server = $servers[$i];
           $con = memcache_connect($server['host']);
           //$memcache = &new Memcache;
           //$con = $memcache->connect($server['host']);
           if (!($con == false)) {
               $this->connections[] = &$con;
   function _getConForKey($key) {
       $hashCode = 0;
       for ($i = 0, $len = strlen($key); $i < $len; $i++) {
           $hashCode = (int)(($hashCode*33)+ord($key[$i])) & 0x7fffffff;
       if (($ns = count($this->connections)) > 0) {
           return $this->connections[$hashCode%$ns];
           //return $this->connections[0];
       return false;
   function debug($on_off) {
       $result = false;
       for ($i = 0; $i < count($this->connections); $i++) {
           if ($this->connections[$i]->debug($on_off)) $result = true;
       return $result;
   function flush() {
       $result = false;
       for ($i = 0; $i < count($this->connections); $i++) {
           if ($this->connections[$i]->flush()) $result = true;
       return $result;
   /// The following are not implemented:
   function get($key) {
       if (is_array($key)) {
           $dest = array();
           foreach ($key as $subkey) {
           $val = get($subkey);
           if (!($val === false)) $dest[$subkey] = $val;
           return $dest;
       } else {
           $conn = &$this->_getConForKey($key);
           return $conn->get($key);
   function set($key, $var, $compress=0, $expire=0) {
       $conn = &$this->_getConForKey($key);
       return $conn->set($key, $var, $compress, $expire);
   function add($key, $var, $compress=0, $expire=0) {
       $conn = &$this->_getConForKey($key);
       return $conn->add($key, $var, $compress, $expire);
   function replace($key, $var, $compress=0, $expire=0) {
       $conn = &$this->_getConForKey($key);
       return $conn->replace($key, $var, $compress, $expire);
   function delete($key, $timeout=0) {
       $conn = &$this->_getConForKey($key);
       return $conn->delete($key, $timeout);
   function increment($key, $value=1) {
       $conn = &$this->_getConForKey($key);
       return $conn->increment($key, $value);
   function decrement($key, $value=1) {
       $conn = &$this->_getConForKey($key);
       return $conn->decrement($key, $value);
   function showStats($server=null) {
       $stats_out = '';
       if($server == null) {
           foreach($this->connections as $conn) {  
               $server = $this->_servers[$i];
               $stats_array = memcache_get_stats($conn);
               $stats_out .= "</br><b>Server: ".$server['host'].": </b><br/>";
               foreach($stats_array as $key => $val) {
                   $stats_out .= "$key => $val <br/>";
       return $stats_out;


An improvement to the above:
The above class will cause an error if all cache servers are down.  The preferred behavior is to just have a cache miss (or take no action in the case of write operations) and return false, so the app can run in non-cached mode if all cache servers are down.
To make this happen, simply change the connection usage to look something like this in each affected function.  This code is for the get() function:
   $con = $this->_getConForKey($key);
   if ($con === false) return false;
   return $con->get($key);
Similarly, the affected code in the set() function would look like this:
$con = $this->_getConForKey($key);
if ($con === false) return false;
return $con->set($key, $var, $compress, $expire);
Modify each function accordingly, and if all of your cache servers are down, you can still function (although more slowly due to the 100% cache miss rate).

Change Language

Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Haru PDF Functions
hash Functions
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker