Memcached comma...login
Memcached command operation manual
author:php.cn  update time:2022-04-13 17:53:40

PHP connects to Memcached service


In the previous chapter, we have introduced how to install the Memcached service. Next, we will introduce how to use the Memcached service in PHP.

PHP Memcache extension installation

PHP Memcache extension package download address: http://pecl.php.net/package/memcache, you can download the latest stable package ( stable).

wget http://pecl.php.net/get/memcache-2.2.7.tgz               
tar -zxvf memcache-2.2.7.tgz
cd memcache-2.2.7
/usr/local/php/bin/phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make && make install

If you are using the PHP7 version, you need to download the specified branch:

git clone -b php7 https://github.com/php-memcached-dev/php-memcached.git

If your system has not compiled libmemcached, download and compile it: https:// launchpad.net/libmemcached/+download

Note: /usr/local/php/ is the installation path of PHP and needs to be adjusted according to the actual directory you installed.

After successful installation, the location of your memcache.so extension will be displayed, such as mine:

Installing shared extensions:     /usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/

Finally we need to add this extension to php, open your php.ini file in Finally add the following content:

[Memcache]
extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/"
extension = memcache.so

Restart php after adding it. I am using the nginx+php-fpm process so the command is as follows:

kill -USR2 `cat /usr/local/php/var/run/php-fpm.pid`

If it is apache, use the following command:

/usr/local/apache2/bin/apachectl restart

Check the installation results

/usr/local/php/bin/php -m | grep memcache

If the installation is successful, it will output: memcache.

Or access the phpinfo() function through the browser to view, as shown below:

memcache-php

PHP connects to Memcached

<?php
$memcache = new Memcache;             //创建一个memcache对象
$memcache->connect('localhost', 11211) or die ("Could not connect"); //连接Memcached服务器
$memcache->set('key', 'test');        //设置一个变量到内存中,名称是key 值是test
$get_value = $memcache->get('key');   //从内存中取出key的值
echo $get_value;
?>

For more PHP operations on Memcached, please refer to :http://php.net/manual/zh/book.memcache.php

php.cn