Skip to content

Instantly share code, notes, and snippets.

@jcefoli
Last active November 21, 2022 11:11
Show Gist options
  • Save jcefoli/1f35cb87b333c427bcf6 to your computer and use it in GitHub Desktop.
Save jcefoli/1f35cb87b333c427bcf6 to your computer and use it in GitHub Desktop.
List All Key/Value Pairs in Redis using the Predis Library. Assumes that Redis is running locally on default port 6379 with no password auth
<?
//Include Predis library. See https://github.com/nrk/predis for more info
require "Predis/Autoloader.php";
//Connect to Redis
Predis\Autoloader::register();
try {
$redis = new Predis\Client();
$redis = new Predis\Client(array(
"scheme" => "tcp",
"host" => "127.0.0.1"))
;
}
catch (Exception $e) {
echo "Couldn't connect to Redis";
echo $e->getMessage();
}
//Get list of all keys. This creates an array of keys from the redis-cli output of "KEYS *"
$list = $redis->keys("*");
//Optional: Sort Keys alphabetically
sort($list);
//Loop through list of keys
foreach ($list as $key)
{
//Get Value of Key from Redis
$value = $redis->get($key);
//Print Key/value Pairs
echo "<b>Key:</b> $key <br /><b>Value:</b> $value <br /><br />";
}
//Disconnect from Redis
$redis->disconnect();
?>
@DianaBabenko
Copy link

thanks, it's works)

@th-lange
Copy link

While this works and is a correct solution,
just keep in mind that some cloud Redis options do not support the "key *" command - as it is very expensive.

A workaround to this is described here:

use Predis\Collection\Iterator;

$client = ...;
$pattern = 'foo*';

foreach (new Iterator\Keyspace($client, $pattern) as $key) {
    ...
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment