How do sessions work in PHP, and what problems appear when you run multiple servers?
session_start() looks for a session id in a cookie. If there is none, PHP generates one, sets the cookie, and creates a store; if there is, PHP loads the matching data into $_SESSION. The data lives on the server; only the id travels to the browser.
By default the store is a file in the server's temp directory. That is precisely what breaks behind a load balancer: a user's first request writes a session file on server A, their second request goes to server B, which finds nothing, and they appear logged out at random.
The fixes, in order of preference:
- A shared session store — Redis or Memcached via
session.save_handler. Fast, and scales to any number of servers. This is the standard answer. - A database handler — slower but durable and easy to inspect.
- Sticky sessions at the load balancer — the least good option, because it undermines even load distribution and loses sessions when an instance is replaced.
Security points worth adding: call session_regenerate_id(true) immediately after login to prevent session fixation, and set the cookie httponly, secure, and samesite.





