How to set password for Redis?

Redis is an open source in-memory data structure store which is often used as a cache server. It supports a light-weight authentication method that allows you to edit the Redis configuration file to enable authentication.

Open redis.conf file and find this line:

Then uncomment this line and replace “foobared” with the password you want. In order to be secure, the password you set must be long and complex.

  • Open redis.conf file and find this line:
# requirepass foobared
  • Then uncomment this line and replace “foobared” with the password you want. In order to be secure, the password you set must be long and complex.
requirepass my_new_password
  • Restart redis server.

There is another way to set password:

# set new password
127.0.0.1:6379> config set requirepass my_new_password
OK
# get password
127.0.0.1:6379> config get requirepass
(error) NOAUTH Authentication required.
# verify 
127.0.0.1:6379> auth my_new_password
OK
127.0.0.1:6379> config get requirepass
1) "requirepass"
2) "my_new_password"

Notice: if the password is not set in the configuration file, it will be invalid after Redis server restarts.

Now let’s have a try with PHP. Check out this article If you don’t have a Redis driver installed in PHP.

$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);

if (!$redis->auth('my_new_password')) {
        die('password is incorrect');
}
echo $redis->ping();

If everything goes well, the above script will show pong result.

RSS