Changing the Session ID

One common attack against websites that are secured with sessions is that the session ID of a user is somehow taken (for instance, by analyzing HTTP_REFERER entries in HTTP requests) and then used to impersonate that specific user.


This is hard to battle, but one convenient way to make it harder for attackers is to change the session ID whenever something "important" happens, such as the user signing in. For instance, Amazon requires users who are already authenticated with their cookie to sign in again when they want to order something.

Changing the Session ID
  echo 'Old: ' . session_id();
  echo '<br />New: ' . session_id();

In this case, the function session_regenerate_id() just changes the current session ID but leaves all data intact. This is shown in the preceding code, in which the current session ID (both old and new) is retrieved using the session_id() function. Figure shows a possible output of this script.

Two session IDs, one is old and one is new.

This code uses output bufferingob_start() and ob_end_flush()because session_regenerate_id() must also be called before any HTML output is sent to the client.