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.

fine

Its looking fine.... Its usefull.

Submitted by Prajapati (not verified) on Sat, 04/26/2008 - 18:18.
It works!

Thanks, I was looking exactly for somethin similar, grat job

Submitted by Alberto (not verified) on Wed, 09/03/2008 - 18:28.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd><pre><blockquote>
  • Lines and paragraphs break automatically.
  • Insert Flickr images: [flickr-photo:id=230452326,size=s] or [flickr-photoset:id=72157594262419167,size=m].

More information about formatting options