Sameer Zahid
Sameer Zahid

Reputation: 583

Where to put session_regenerate_id() in a login script in PHP

I am creating a log in script and I need to know where exactly should I put the session_regenerate_id() function when I want to log the user in. The way I do it is like this:

    $user_id = $general->login($username, $password);

$_SESSION['user_id'] = $user_id;

The log in function basically returns the user's auto-incremental id in the table, and I store that in the $_SESSION variable as shown above. I have only showed the part of the logic where I use the Session variable because I just know where I should put session_regenerate_id to avoid session fixation attack. Before or after I assign the value?

Like so:

    session_regenerate_id(true); 

$_SESSION['user_id'] = $user_id;

Or after, like so:

$_SESSION['user_id'] = $user_id;

    session_regenerate_id(true); 

Thank you.

Upvotes: 0

Views: 802

Answers (2)

Kyoma
Kyoma

Reputation: 209

From Session Management Basics:

session_regenerate_id() must be called prior to setting the authentication information to $_SESSION.

So, you have to place it before $_SESSION.

Upvotes: 0

fdreger
fdreger

Reputation: 12505

It does not matter, as long as you do it in the same request as storing users' id in the session (standard restrictions apply, eg. if you don't cache your output you are not allowed to print any characters before executing session_regenerate_id). Either way you call it, it will prevent others from using the old session id to access the session that has user_id stored.

Upvotes: 3

Related Questions