Latest web development tutorials

PHP Memcached service connection

In the previous section we have described how to install the Memcached service, then we tell you how to use PHP Memcached service.

PHP Memcache extension installation

PHP Memcache expansion pack Download: 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 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 is not compiled libmemcached, then compile it to download: https://launchpad.net/libmemcached/+download

Note: / usr / local / php / php for the installation path, you need to adjust your actual installation directory.

It will show you memcache.so extended position after a successful installation, for example, I:

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 add the following at the end:

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

After addition restart php, I'm using nginx + php-fpm process so the command is as follows:

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

If apache, use the following command:

/usr/local/apache2/bin/apachectl restart

Checking the installation results

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

Successful installation will output: memcache.

Through a browser or visit phpinfo () function to see, as shown below:

memcache-php

PHP Memcached connection

<?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;
?>

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