write me a php test code to connect to redis with password
- User
write me a php test code to connect to redis with password
Assistant
write me a php test code to connect to redis with password
Okay, here's a PHP test script to connect to Redis with a password using the most common PHP Redis client library, phpredis (the C extension).
Prerequisites:
redis.conf, uncomment or add: requirepass your_strong_passwordphpredis extension installed and enabled in your php.ini.
pecl install redis and then add extension=redis.so (Linux) or extension=php_redis.dll (Windows) to your php.ini.php -m | grep redis or by checking phpinfo().PHP Test Code:
<?php
/**
* PHP Redis Connection Test Script with Password
*
* This script attempts to connect to a Redis server, authenticate with a password,
* perform a simple SET/GET operation, and then clean up.
*
*/
// --- Configuration ---
$redisHost = '127.0.0.1'; // Your Redis server host
$redisPort = 6379; // Your Redis server port
$redisPassword = 'your_strong_password'; // <-- IMPORTANT: Change this to your actual Redis password!
$testKey = 'myTestKey';
$testValue = 'Hello from PHP Redis with password!';
// --- Script Start ---
echo "--- PHP Redis Password Connection Test ---\n\n";
// 1. Check if the Redis extension is loaded
if (!extension_loaded('redis')) {
die("Error: PHP Redis extension not loaded. Please install and enable it.\n");
}
// 2. Create a new Redis object
$redis = new Redis();
try {
// 3. Connect to Redis server
echo "Attempting to connect to Redis at $redisHost:$redisPort...\n";
if (!$redis->connect($redisHost, $redisPort)) {
// connect() returns false on failure. It might also throw an exception depending on configuration.
throw new Exception("Could not connect to Redis server.");
}
echo "Successfully connected to Redis.\n";
// 4. Authenticate with password
echo "Attempting to authenticate with password...\n";
if (!$redis->auth($redisPassword)) {
// auth() returns false on authentication failure
throw new Exception("Authentication failed. Please check your password.");
}
echo "Successfully authenticated with Redis.\n";
// 5. Perform a simple write operation (SET)
echo "Setting key '$testKey' with value '$testValue'...\n";
if (!$redis->set($testKey, $testValue)) {
throw new Exception("Failed to set key '$testKey'.");
}
echo "Key '$testKey' set successfully.\n";
// 6. Perform a simple read operation (GET)
echo "Getting value for key '$testKey'...\n";
$retrievedValue = $redis->get($testKey);
if ($retrievedValue === false) {
throw new Exception("Failed to get key '$testKey' or key does not exist.");
}
echo "Retrieved value for '$testKey': '$retrievedValue'\n";
// 7. Verify the retrieved value
if ($retrievedValue === $testValue) {
echo "\nSuccess! Retrieved value matches original. Redis connection and authentication are working.\n";
} else {
echo "\nWarning! Retrieved value does NOT match original. Something might be wrong.\n";
}
// 8. Clean up: Delete the test key (optional, but good practice)
echo "Deleting test key '$testKey'...\n";
if ($redis->del($testKey)) {
echo "Test key '$testKey' deleted successfully.\n";
} else {
echo "Failed to delete test key '$testKey'.\n";
}
} catch (Exception $e) {
// Catch any exceptions that occurred during the process
echo "\nAn error occurred: " . $e->getMessage() . "\n";
} finally {
// 9. Close the Redis connection
// Always good to close the connection when done, especially in long-running scripts
if ($redis->isConnected()) { // Check if connected before trying to close
$redis->close();
echo "Redis connection closed.\n";
}
}
echo "\n--- Test Complete ---\n";
?>
How to Run the Test:
redis_test.php (or any other .php filename).'your_strong_password' in the $redisPassword variable to the actual password you've configured in your redis.conf.php redis_test.php
Expected Output (on success):
--- PHP Redis Password Connection Test ---
Attempting to connect to Redis at 127.0.0.1:6379...
Successfully connected to Redis.
Attempting to authenticate with password...
Successfully authenticated with Redis.
Setting key 'myTestKey' with value 'Hello from PHP Redis with password!'...
Key 'myTestKey' set successfully.
Getting value for key 'myTestKey'...
Retrieved value for 'myTestKey': 'Hello from PHP Redis with password!'
Success! Retrieved value matches original. Redis connection and authentication are working.
Deleting test key 'myTestKey'...
Test key 'myTestKey' deleted successfully.
Redis connection closed.
--- Test Complete ---
Common Errors and Troubleshooting:
Error: PHP Redis extension not loaded.: Install and enable the phpredis extension.Could not connect to Redis server.:
redis-cli ping should return PONG).redis_test.php?127.0.0.1 (or the IP you're trying to connect to)? Check bind in redis.conf.Authentication failed. Please check your password.:
$redisPassword in your PHP script exactly matches requirepass in redis.conf.redis.conf?Failed to set key... / Failed to get key...: This could indicate a permissions issue on the Redis server, or the authentication might have silently failed (though the auth() check should catch this).This script provides a robust way to test your PHP application's ability to connect and authenticate with a password-protected Redis instance.