The Hidden Cost of KEYS in PHP and Redis
You are seeing different results because your PHP application is interacting with a different instance of Redis than the one you are querying from the shell. In distributed systems, it is common to have multiple processes or services running, but they must connect to the exact same backend server to share state.
The discrepancy you encountered stems from where the connection is being established. When you run redis-cli on your terminal, it connects directly to the Redis server listening on 127.0.0.1:6379. However, your PHP script might be connecting to a different host or port, or it could be that the Redis process used by your web server (e.g., via the XDebug debugger or an internal application server) is distinct from the CLI tool.
If you are running this in a development environment where everything should share the same memory space, the most likely culprit is that the PHP script is connecting to a different machine entirely, perhaps via localhost resolving to an external IP, or the Redis daemon started by your web server (like Apache or Nginx) is not the one accepting connections on port 6379.
To verify this, inspect the output of your PHP connection and ensure it targets the same endpoint as your shell session. If both are truly pointing to 127.0.0.1:6379, then the issue is likely that the PHP process does not have permission to write to the Redis instance, or the data is being evicted due to memory limits before you can read it back.
Implementing KEYS with phpredis
Once you confirm that your PHP script and shell are talking to the same server, retrieving all keys is straightforward using the phpredis extension. The syntax mirrors the Redis CLI command, but instead of sending a string, you invoke a method on the object instance.
Here is how you correctly fetch all matching keys:
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// Ensure the connection is active before querying
if (!$redis->ping()) {
die('Connection failed');
}
// Retrieve all keys matching the pattern '*'
$allKeys = $redis->keys('*');
print_r($allKeys);
This code creates a new Redis instance, establishes a TCP connection to the server, and calls the keys() method with the wildcard pattern *. The phpredis extension will execute the KEYS * command on the server and return an array of all string keys currently in the database.
Why You Might See Nothing
If you still see an empty array despite the shell showing results, consider these factors:
- Connection Mismatch: Double-check that your PHP script is not connecting to a different IP address. Sometimes DNS resolution or environment variables can redirect
localhostto a different machine. - Memory Eviction: If your Redis instance has a strict memory limit and the keys are expiring (if you set an expiration time), they might disappear between setting and getting them. However, since
KEYSis synchronous, this usually manifests as timing issues rather than a complete disconnect. - Permissions: Ensure that the user running your PHP script has the necessary permissions to interact with the Redis socket or TCP port. If the process is restricted, it might connect but fail silently or return empty results depending on configuration.
Performance Warning: The KEYS Command
While keys('*') works perfectly for debugging and small datasets, you must exercise extreme caution when using it in production applications with large databases. The KEYS command blocks the server until it has scanned the entire database to find matches. As your dataset grows, this operation becomes increasingly expensive and can cause significant latency for other requests waiting on that Redis instance.
For high-performance scenarios involving pattern matching, the recommended approach is to use SCAN. Unlike KEYS, which returns all results in a single blocking call, SCAN iterates through the database incrementally. This allows other commands to proceed while the scan is happening, making it non-blocking and safer for production workloads.
// Example of using SCAN instead of KEYS
$cursor = $redis->scan(0, 'pattern', 10); // Start with cursor 0
while ($cursor !== false) {
foreach ($cursor as $key) {
// Process each key
}
$cursor = $redis->scan($cursor, 'pattern', 10); // Continue iteration
}
By switching to SCAN for production use cases, you ensure that your application remains responsive even under heavy load.