Last Updated: February 25, 2016
·
9.796K
· markus-perl

PHP - Memcache - list Keys

This method lists all stored memcache keys by dumping the cache.

/**
 * @ param string $server
 * @ param int $port
 * @ param int $limit
 * @ return array
 */
public function getMemcacheKeys ($server, $port, $limit = 10000)
{
    $keysFound = array();

    $options = $this->_options;
    $server = $options['servers'][0];
    $memcache = new Memcache;
    $memcache->connect($server, $port = 11211, 5);

    $slabs = $memcache->getExtendedStats('slabs');
    foreach ($slabs as $serverSlabs) {
        foreach ($serverSlabs as $slabId => $slabMeta) {
            try {
                $cacheDump = $memcache->getExtendedStats('cachedump', (int) $slabId, 1000);
            } catch (Exception $e) {
                continue;
            }

            if (!is_array($cacheDump)) {
                continue;
            }

            foreach ($cacheDump as $dump) {

                if (!is_array($dump)) {
                    continue;
                }

                foreach ($dump as $key => $value) {
                    $keysFound[] = $key;

                    if (count($keysFound) == $limit) {
                        return $keysFound;
                    }
                }
            }
        }
    }

    return $keysFound;
}

2 Responses
Add your response

great , thanks

over 1 year ago ·

I can use the function getExtendedStats without arguments ; when i add the arguments 'items' and 'slabs' i don't get anything...do i need specific configuration to use arguments with that function or what ? plz help , any idea would be appreciated.thanks.

over 1 year ago ·