🐘 PHP Intermediate

What is PHP session security best practices?

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.