When and why I should use session_regenerate_id()?

What is session_regenerate_id()?

As the function name says, it is a function that will replace the current session ID with a new one, and keep the current session information.

What does it do?

It mainly helps prevent session fixation attacks. Session fixation attacks is where a malicious user tries to exploit the vulnerability in a system to fixate (set) the session ID (SID) of another user. By doing so, they will get complete access as the original user and be able to do tasks that would otherwise require authentication.

To prevent such attacks, assign the user a new session ID using session_regenerate_id() when he successfully signs in (or for every X requests). Now only he has the session ID, and your old (fixated) session ID is no longer valid.

When should I use session_regenerate_id()?

As symbecean points out in the comments below, the session id must be changed at any transition in authentication state and only at authentication transitions.

Further reading:

Leave a Comment