What is PHP session security best practices?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
Answer
Sessions are a common attack vector. Best practices: Regenerate session ID after login (session_regenerate_id(true)) to prevent session fixation attacks. Use HTTPS and set session.cookie_secure = true so the session cookie is only sent over encrypted connections. Set session.cookie_httponly = true to prevent JavaScript from accessing the session cookie (XSS mitigation). Set session.cookie_samesite = "Lax" or "Strict" for CSRF mitigation. Set a reasonable timeout: track the last activity time in the session and invalidate stale sessions. Do not store sensitive data (credit card numbers, passwords) in sessions. Use Redis or Memcached for session storage in production instead of files (faster, easier to clear on logout). Validate session data server-side — never trust it blindly.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex PHP answers easy to follow.
Previous
What is PHP's Countable interface?
Next
What is the difference between abstract methods and interface methods in PHP?