Regenerate PHP session id
One of my most popular posts is one from 2005 about regenerating session id's in PHP.
Because of this I thought it was about time I wrote an updated post about this topic.
Why should I regenerate the session ID?
One reason. To prevent session hijacking.
Session hijacking is when a hacker get to know a user's session ID, and uses it to pretend he is that user.
When should I regenerate the session ID?
A general rule of thumb is to generate the session ID each time a user changes his access level.
- When a user log in
- When a user log out
- When a user get administrative access
You could also choose to give the user a new ID once in a while, just to play safe.
How?
Easy, at least if you have PHP 5.1.0 or greater.
Then you can just do this:
session_start(); session_regenerate_id(true);
It it important to supply the session_regenerate_id() function with the true argument, in order to destroy the old session ID.
If you use a older PHP version that does not support this (<5.1.0), you should do something like this:
session_start(); $tmp = $_SESSION; session_destroy(); session_start(); $_SESSION = $tmp;
That's it. Easy.
Its looking fine.... Its usefull.
- reply
Submitted by Prajapati (not verified) on Sat, 04/26/2008 - 18:18.Thanks, I was looking exactly for somethin similar, grat job
- reply
Submitted by Alberto (not verified) on Wed, 09/03/2008 - 18:28.Post new comment