Consider my code below:
<?php
session_start();
if(!isset($_SESSION['count'])) $_SESSION['count']=0;
else ++$_SESSION['count'];
echo $_SESSION['count'];
?>
when i call it up on my browser http://localhost/user_login.php?PHPSESSID=1234
when i press reload a few times I see that my counter its increasing, however when i type
http://localhost/user_login.php?PHPSESSID=5678
and reaload a few times I see that it count up again from 0.
When i leave the counter on a different number than the first url and then go back to the first url i see that the number changes back again!! It seems that I have created two different sessions and I could even create more this way !!! Is there any way to prevent from happeneing ?
This approach it's very dangerous the attacker would be able to take over any sessions that has not been deleted or expired.
To prevent this, add a simple check to change the session ID using session_regenerate_id
.
This function keeps all current session variable values, but replaces the session ID with a new one that an attacker can not know.
To do this, check for a special session variable that you arbitrarily invent. If it doesnt exists, you know that this is a new session, so you simply change the session ID and set the special session variable to note the change
Code:
<?php
session_start();
if(!isset($_SESSION['initiated'])){
session_regenerate_id();
$_SESSION['initiated']=1;
}
if(!isset($_SESSION['count'])) $_SESSION['count']=0;
else ++$_SESSION['count'];
echo $_SESSION['count'];
?>
If you want to be ultra paranoid you can even regenerate the session ID on each request.