We're considering moving our php session data to redis.
The setup looks simple. Just set the following in php.ini and restart apache. It should be all set.:
session.save_handler = redis
session.save_path = "tcp://host1:6379"
If possible I would like our users not to notice the migration. Is it possible to move the session data to redis without losing any existing session data?
There is no out-of-the-box solution available right now for what you are asking, but writing a custom script for this task can actually be fairly simple.
Esentially, phpredis stores session data in redis as strings with the following key name format: PHPREDIS_SESSION:$sessionid
, where $sessionid
is the php id of the session, the one retrievable via session_id()
. The session data is "encoded" as a php-session serialized variable (which is a slightly different format to the common php serialize/unserialize, see session_encode).
Now that we know this, there are two possibilities to migrate session data stored in files:
Iterate through every session file (the actual path is set at session.save_path
in your php.ini), read the data and write it back to redis. The files themselves store the php-session serialized representation of the session data, which means the content can be copied as it is directly to redis, and the filenames have the following pattern: sess_$sessionid
, where $sessionid is, you guessed it, the id you'll want to use for your redis keys.
Migrate the data progressively by staying with file based sessions for now, but populating redis in real time as session data is being used, until the amount of sessions stored in redis looks good enough to do the switch. This could be achieved by doing something like:
$redis->set("PHPREDIS_SESSION:".session_id(), session_encode());
Right before each script ends. This method may add a little bit of overhead depending on the amount of data in session and how session_encode works.
Just created such a script in bash and added to my repo.
https://github.com/renasboy/php-redis-migrate-sessions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With