In order to use Memcached with PHP you will need a PHP Memcached client. In the following sections, we will demonstrate the use of PECL memcached, an extension that uses the libmemcached library to provide an API for communicating with Memcached servers as well as a session handler (memcached).
PECL memcached’s installation instructions are given in its “Installation” page. To install it, use the following command:
pecl install memcached
Once installed, you should review the
/etc/php5/mods-available/memcached.ini file or your site’s
php.ini file and verify the following setting in it:
memcached.use_sasl) – to use a SASL-enabled Memcached Cloud bucket, enable this setting by setting it to 1
Note: if you’ve installed PECL memcached, you should consider restarting your web server to apply the changes.
The following code creates a connection to Memcached using PECL memcached:
<?php $mc = new Memcached(); $mc->setOption(Memcached::OPT_BINARY_PROTOCOL, true); $mc->addServer('hostname.redis.com', 11211); $mc->setSaslAuthData('username', 'password'); ?>
To adapt this example to your code, make sure that you replace the following values with those of your bucket:
addServershould be your bucket’s hostname or IP address
addServershould be your bucket’s port
setSaslAuthDatashould be your bucket’s username
setSaslAuthDatashould be your bucket’s password
Once connected to Memcached, you can start reading and writing data. The following code snippet writes the value
bar to the Memcached key
foo, reads it back, and prints it:
// open a connection to Memcached ... $mc->set('foo', 'bar'); $value = $mc->get('foo'); echo $value;
The output of the above code should be:
$ php memcached.php bar
Redis Enterprise enables running Redis datasets in a highly available and auto-scalable manner, with predictable top performance.
Redis Enterprise Software lets you install an enterprise grade Memcached cluster in your environment of choice, whether an on-premises data-center or your preferred cloud platform. It gives you full control of your data and configuration – no clustering or sharding knowledge required!
Memcached Cloud is a fully managed cloud service for hosting and running Memcached datasets in a highly available and scalable manner, with predictable and stable top performance. It provides a storage engine for standard Memcached, as well as in-memory replication and instant auto-failover within the same data center or across data centers. The service completely frees developers from dealing with nodes, clusters, scaling, data persistence issues or failure recovery.
For more information on using Redis’ products and services with PHP please see the Howto page.
By continuing to use this site, you consent to our updated privacy agreement. You can change your cookie settings at any time but parts of our site will not function correctly without them.