What is the distinct difference between session_id($randomString)
and session_regenerate_id()
? Both seem to change session id:
OK, so I did some testing to find the differences in the three different options (session_id($id)
after session_start()
, session_regenerate_id()
and session_regenerate_id(true)
). This is the result of what actually happens:
Calling the session id function after session_start will change the session id. At the end of the page load, the current session contents will write a new session file. This will leave the old session file as well and it won't be updated with any changes. However, session_id
doesn't send out a new session cookie. This is done by session_start
, even when session_id
is called before session_start
. On the next page load, the old session id is passed and loaded with the same data as the start of the last page load (new session changes would have been saved to the new id).
session_regenerate_id()
will create and change the session id, transferring the session to the new file and send out the cookie. Passing true
as an argument will also delete the old session file, omitting the argument will leave it.
As far as session fixation, both session_id($id)
and session_regenerate_id()
would actually be worse as you are creating new sessions while leaving the old session files around to be hijacked. The only option that might help with fixation would be to call session_regenerate_id(true)
passing the argument.
The session_id
function will just change the session id and update the session cookie on the client.
The session_regenerate_id
function will act like the session_id
one with the additional session migration on the server.
In fact as you can read from the docs of the session_id
function, it needs to be called before the session_start
function, otherwise it may be lay you to a session loss.
Example:
Conditions:
Description:
/tmp/sess_1234abc
./tmp/sess_SESSID
in this case /tmp/sess_1234abc
)session_id
function/tmp/sess_MyTestSession
file but the session has not been changed by the session_id
function so is still /tmp/sess_1234abc
!So if you want to prevent session fixation the way to go is definitely session_regenerate_id
in a way session_regenarate_id()
includes session_id()
internally.
session_id()
is a way to get or set the session identifier. It doesn't handle sessionsess_*
files. You place it beforesession_start
in order to indicate the session identifier. Cookie creation and session file creation aresession_start
work later on.
On the other hand
session_regenarate_id()
is something that does not simply set the session identifier but also get your session data from the oldsess_*
file and append it to the new one (with the random id) and create a newcookie
. Depending on thedelete_old_session
parameter insession_regenarate_id()
if set totrue
it will delete the old associated session file, otherwise it will remain as a file but it will be empty of all session data.