Sesiones seguras en PHP: cookies, regenerar el ID y logout (guía rápida)
La sesión de PHP es donde vive el «he iniciado sesión como este usuario», así que si está mal configurada puede convertirse en un punto débil: quien consiga manipularla puede suplantar a otra persona sin conocer su contraseña. Aquí repasamos cómo configurar sesiones seguras en PHP: cookies bien configuradas, regeneración del ID tras el login y qué conviene evitar guardar dentro de la sesión. Qué…
PHP sessions represent the "I have logged in as this user" state, making them a prime target for exploitation if improperly configured. A compromised session can allow unauthorized access to a user's account without needing their password. This report explains how to configure secure PHP sessions, including cookie settings, ID regeneration after login, and proper logout procedures.
Two common attacks target insecure sessions: Session fixation and Session hijacking. To mitigate these threats, follow these guidelines. First, configure session cookies with strict security parameters before calling session_start(). Set the cookie to be HttpOnly (preventing JavaScript access), Secure (transmitted only over HTTPS), SameSite (prevents cross-domain requests), and specify a lifetime (0 to expire on browser close).
Next, regenerate the session ID after successful login using session_regenerate_id(true). This creates a new session ID and clears the old one from the server, preventing session fixation attacks. Avoid storing sensitive data within the session, such as passwords or credit card information. Instead, store only the user's identifier and retrieve additional data from the database as needed.
Implement proper logout procedures to destroy the session, clear the cookie, and terminate the server-side session. Reset the $_SESSION array, set a blank cookie using session_get_cookie_params(), and call session_destroy(). Adjust the session.gc_maxlifetime parameter to define how long sessions remain inactive before being automatically cleared.
For applications with strict security requirements, set the lifetime to 1800 seconds (30 minutes). Lastly, ensure all communication occurs over HTTPS to leverage the secure cookie setting. For a comprehensive guide, refer to the OWASP Session Management Cheat Sheet.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to