ElastiCache client implementation in PHP

AWS ElastiCache clustering is implemented by a custom memcached php module that knows how to get the current list of EC hosts from an configuration endpoint. This module is not currently available for PHP 5.6 (which the latest Elastic Beanstalk is using).

This is a pure PHP implementation of a function that takes the name of the configuration endpoint and returns an array of memcached hosts.

function elasticache_cluster_config($ep) {
  $ep = explode(':', $ep);
  if (count($ep) == 1) {
    $ep[1] = 11211;
  $fp = fsockopen($ep[0], $ep[1], $errno, $errstr, 2);

  if (!$fp) {
    error_log(sprintf('Memcached config connection failed: %s/%s', $errstr, $errno));
    echo "An internal error occurredn";

  fwrite($fp, "config get clusterrn");
  $status = fgets($fp);

  // If this is not ElastiCache, return the server itself
  if (strpos($status, 'CONFIG') != 0) {
    fwrite($fp, "QUITrn");
    return array($ep);

  $mods = fgets($fp);
  $cluster = fgets($fp);
  fwrite($fp, "QUITrn");

  $memcache = array();
  foreach (explode(' ', $cluster) as $server) {
    $server = explode('|', $server);
    $memcache[] = $server[0] . ':' . $server[2];

  return $memcache;

$memcached_servers = array('default' => elasticache_cluster_config(""));

No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Comment replies are not available offline