PHP Connection to Memcached Service
In previous chapters, we have introduced how to install the Memcached service. Next, we will explain how PHP can use the Memcached service.
PHP Memcache Extension Installation
PHP Memcache extension package download link: 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
Note: /usr/local/php/ is the installation path of PHP, which needs to be adjusted according to your actual installation directory.
After successful installation, the location of your memcache.so extension will be displayed, for example:
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 content 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 am using 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.
Alternatively, you can check by accessing the phpinfo() function through a browser, as shown in the image below:
PHP Connection to Memcached
<?php
$memcache = new Memcache; // Create a memcache object
$memcache->connect('localhost', 11211) or die ("Could not connect"); // Connect to Memcached server
$memcache->set('key', 'test'); // Set a variable in memory, named 'key' with value 'test'
$get_value = $memcache->get('key'); // Retrieve the value of 'key' from memory
echo $get_value;
?>
For more PHP operations with Memcached, please refer to: http://php.net/manual/zh/book.memcache.php