PHP › Sessions & Cookies

What is session fixation, and how does regenerating the session identifier after a successful login help prevent this attack?

Intermediate

Answer

Session fixation is an attack where an attacker tricks a victim into using a session identifier that the attacker already knows, then waits for the victim to log in, at which point the attacker can use that same known session identifier to access the now authenticated session as if they were the victim, and calling session_regenerate_id immediately after a successful login generates a brand new session identifier for the now authenticated user, invalidating whatever identifier existed beforehand and making it useless to an attacker even if they had somehow set it in advance.
if (password_verify($inputPassword, $storedHash)) {
    session_regenerate_id(true);
    $_SESSION['user_id'] = $user['id'];
}
Real-world example A login system regenerates the session identifier immediately after verifying a user's password is correct, ensuring that any session identifier an attacker may have previously fixed onto the victim's browser becomes worthless once the victim actually logs in.

Common follow-ups: What does passing true to session_regenerate_id actually do differently compared to passing no argument?;At what other points in an application might it also be wise to regenerate the session identifier?