Skip to content

Instantly share code, notes, and snippets.

@patricknelson
Last active October 1, 2021 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patricknelson/de195f0ba23a9c5583ee79c7038bb3c5 to your computer and use it in GitHub Desktop.
Save patricknelson/de195f0ba23a9c5583ee79c7038bb3c5 to your computer and use it in GitHub Desktop.
List all keys in older Memcache PHP extension
<?php
/**
* Goes through all configured memcached slabs on the provided pre-configured Memcache object
*
* IMPORTANT: This is for the older and more limited https://pecl.php.net/package/memcache (no "d" suffix) and
* NOT for https://pecl.php.net/package/memcached (has the "d" suffix)!
*
* Inspired by (and modified from): https://coderwall.com/p/imot3w/php-memcache-list-keys
*
* @param Memcache $memcache
* @param int $limit
* @return array
*/
function getMemcacheKeys(Memcache $memcache, $limit = 10000) {
$keysFound = array();
$slabs = $memcache->getExtendedStats('slabs');
foreach($slabs as $serverSlabs) {
foreach($serverSlabs as $slabId => $slabMeta) {
// Move on if not an actual integer (e.g. skip active_slabs).
if (!is_numeric($slabId)) continue;
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment