php 的 memcache 與 memcached

最後更新: 2024-05-30

memcache v.s. memcached


  • First Release Date: 2004-06-08
  • External Dependency: None
  • Debian Package: php8.1-memcache


  • First Release Date: 2009-01-29 (beta)
  • External Dependency: libmemcached
  • Debian Package: php8.1-memcached

* php memcached is faster than memcache


  • Centos 7 's php70 connect memcached
  • PHP Session 存放在 memcached
  • PHP Code Connect Memcache
  • Durpal6 與 memcache


Centos 7 's php70 connect memcached


# php 7 support memcache

yum list | grep php7 | grep devel

php70u-devel.x86_64                     7.0.9-1.ius.el7                ius
php70u-pecl-apcu-devel.x86_64           5.1.5-2.ius.el7                ius

yum install php70u-devel

yum groupinstall "Development Tools"

yum install zlib-devel memcached-devel libmemcached-devel

yum install git

# Get source

git clone

cd php-memcached

git checkout php7




make install

# Enable memcached module

echo "" > /etc/php.d/memcached.ini

# Checking

php -m | grep memcached


PHP Session 存放在 memcached


php 的 Default 存放 session 方式及地方

session.save_handler = files
session.save_path = "/var/lib/php/session"

session.use_cookies = 1
# only use cookies to store the session id on the client side
session.use_only_cookies = 1 = PHPSESSID

session.auto_start = 0
session.cookie_lifetime = 0

改用 memcache 存放 session (沒有 "d" 的那個 memcache)




在 Centos 6 上用 httpd 行 php 會有另外的 Session 的 "Local Value" 及 "Master Value"


php_value session.save_handler "files"
php_value session.save_path    "/var/lib/php/session"



PHP Code Connect  Memcache


bool Memcache::close ( void )

# This function doesn't close persistent connections,
# which are closed only during web-server shutdown/restart.

bool Memcache::connect ( string $host [, int $port [, int $timeout ]] )

# The connection, which was opened using Memcache::connect() will be automatically closed at the end of script execution.

string Memcache::get ( string $key [, int &$flags ] )

# returns previously stored data if an item with such key exists

    /* OO API */
    $memcache_obj = new Memcache;
    $memcache_obj->connect('memcache_host', 11211);
    $var = $memcache_obj->get('some_key');
    print $var;


Durpal6 與 memcache


php module:


This extension allows you to work with memcached through handy OO and
procedural interfaces in your php5 applications.

php5-memcached(memcached.ini)   <-- 不是必要的

This extension uses libmemcached library to provide
API for communicating with memcached servers.

php 設定:

# default: standard (PECL extension version >= 2.2.0)
# enable consistent hashing which allows servers to be added or removed
# from the pool without causing keys to be remapped


修改 php:


    $conf = array(
      'cache_inc' => './modules/memcache/',


Panel Setting:

設定: Show memcache statistics at the bottom of each page

# Memcache statistics

# Memcache



Creative Commons license icon Creative Commons license icon