phplaravelredispredisphpredis

PHP Laravel - Redis connection using URL wirh user and pass


I'm trying to do a PHP Redis connection. I explored the phpredis and the predis packages and didn't find a way to include the username and password URL connection string.

This is because I receive a environment variable of the redis connection string in this format: tls://{username}:{password}@{host}:{port}

I can change the order/format of the url string on the environment variable. How do I know the final format of the connection string used on phpredis ou predis? How can I indicate the username / password on the redis URL string, for the predis or phpredis?

I'm not restricted to predis or phpredis. I can use another if you have any suggestion.


Solution

  • Redis has the parameter requirepass for password and no parameter for user. Meaning I do not think a particular user is needed nor specified, unless you can verify otherwise.

    You can convert the url to array params like so

    [
      'host'     => parse_url($url, PHP_URL_HOST),
      'password' => parse_url($url, PHP_URL_PASS),
      'port'     => parse_url($url, PHP_URL_PORT),
      'database' => parse_url($url, PHP_URL_PATH),
    ]
    

    To support your config in both local development and production you need something like this in you config/database.php

    ...
    'default' => ($url = env('REDIS_URL'))
        ? [ // production config
            'host' => parse_url($url, PHP_URL_HOST),
            'password' => parse_url($url, PHP_URL_PASS),
            'port' => parse_url($url, PHP_URL_PORT),
            'database' => parse_url($url, PHP_URL_PATH),
        ]
        : [ // original local config
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD'),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_DB', 0),
        ],
    ...
    

    Note, I assume your env variable is named REDIS_URL, please change that accordingly.