PHP › Sessions & Cookies
How can you store session data in a shared storage system like Redis or a database instead of the default local file storage, and why is this often necessary for applications running on multiple servers?
AdvancedAnswer
PHP's default session storage saves session data as individual files on the local server's file system, which works fine for a single server, but becomes a significant problem for an application running behind a load balancer across multiple servers, since a user's session file might be saved on one server but their next request could be routed to a completely different server that has no access to that file, and implementing a custom session handler backed by shared storage like Redis or a database, accessible equally from every server, solves this by centralizing where session data actually lives.
session_set_save_handler(new RedisSessionHandler($redisClient));
session_start();Real-world example A popular web application running across ten different load balanced servers stores all session data in a centralized Redis instance, ensuring a user's session remains valid and consistent no matter which specific server happens to handle each of their individual requests.