PHP Connection to Memcached Service
In previous chapters, we have introduced how to install the Memcached service. Next, we will show you how to use Memcached service with 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
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 use nginx + php-fpm process, so the command is as follows:
kill -USR2 `cat /usr/local/php/var/run/php-fpm.pid`
If you are using apache, use the following command:
/usr/local/apache2/bin/apachectl restart
Check the installation result:
/usr/local/php/bin/php -m | grep memcache
Successful installation will output: memcache.
Alternatively, you can view it through the browser by accessing the phpinfo() function, as shown in the figure 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, name is key and value is 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