PHP Connect to Memcached Service
In the previous chapters we introduced how to install the Memcached service; next we will introduce how PHP uses the Memcached service.
PHP Memcache Extension Installation
PHP Memcache extension package download address:http://pecl.php.net/package/memcache, where 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
Note:/usr/local/php/ is the php installation path; adjust it according to your actual installation directory.
After a successful installation, the location of your memcache.so extension will be shown, for example 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 and add the following at the end:
[Memcache]
extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/"
extension = memcache.so
After adding, restart php; I use the nginx+php-fpm process, so the command is as follows:
kill -USR2 `cat /usr/local/php/var/run/php-fpm.pid`
If using apache, use the following command:
/usr/local/apache2/bin/apachectl restart
Check the installation result
/usr/local/php/bin/php -m | grep memcache
A successful installation will output: memcache.
Or view it by accessing the phpinfo() function in a browser, as shown below:
PHP Connect to Memcached
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