Search code examples
phpsessionsession-fixation

When and why I should use session_regenerate_id()?


Why and when should I use the session_regenerate_id() function in php? Should I always use it after I use the session_start()? I've read that I have to use it to prevent session fixation, is this the only reason?


Solution

  • 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: