PHP session hijack

670 Views Asked by At

Possible Duplicate:
PHP Session Fixation / Hijacking

I've been using $_SESSION superglobal a lot and heavily.

However the situation is like this:

Once the user is logged I want to keep track of his ID(MySQL table). I can easily insert the id into $_SESSION['id'] = $user_id;

After all I can use that variable across the pages on my site. What's on my mind is - user can trick the ID into another. If I would see that there's a simple number then I can change it a bit and see what happens - I want to prevent this as it can cause a lot of problems as user ID would be used for adding, deleting, editing entries inside the database.

Is session_regenerate_id() just enough to keep my session safe from hijack ?

Conclusion: Cookie only stores session identificator - all the values are on the server and never get passed to the client side. Read about session fixation/hijacking on StackOverflow

3

There are 3 best solutions below

5
On BEST ANSWER

The user has no acccess to $_SESSION['id']. He can not modify a variable that's kept on your server (see session doc).

session_regenerate_id() has a different purpose. It resets the cookie SID. That's the handle that differentiates users and sessions. It only makes sense to use if you have a secondary identifier (IP or user agent string) to verify. It's main purpose is preventing stale or intersecting sessions. Again, see the manual.

0
On

If I were you I'd have a table in your database that stored a user_id and a session_hash. Possibly a date_expires as well. Then when a user logs in you create a hash based on their id and maybe a random salt, store that in the database as well as the session variable. That way if they change that value on their side, the chances of them matching some other stored value in your database is very unlikely. Along with this if the user performs any operations on their account you just check the database table for their hash to get their real id and then follow through with the operation like you normally would.

4
On

One option would be to hash it and then use that same hash in your database.

Example:

$_SESSION['id'] = md5($user_id);

$query = "SELECT * from database_table where md5(database_table.user_id) = " . $_SESSION['id'];