Here's the code. It's a simple operation to check that a session ID isn't being spoofed by verifying the IP address:
session_start();
$session_ip_address = $_SERVER['REMOTE_ADDR'];
if((!isset($_SESSION['SESSION_IP_ADDRESS'])) || !$_SESSION['SESSION_IP_ADDRESS']) {
$_SESSION['SESSION_IP_ADDRESS'] = $session_ip_address;
}
if($_SESSION['SESSION_IP_ADDRESS'] != $_SERVER['REMOTE_ADDR']) {
session_destroy();
$_SESSION['security_error'] = true;
}
If I insert var_dump($_SESSION)
right after session_start()
and again at the end of the script, then the very first time I run the code (without a session cookie set) I see that at first the array is empty, then it has my IP address assigned to the key 'SESSION_IP_ADDRESS'. So far, so good. But when I run the code again, now it shows that 'SESSION_IP_ADDRESS' is stored as a reference immediately after the session starts (I can tell by the ampersand prepended to the string). When I run it a third time, I see that 'SESSION_IP_ADDRESS' is now a null reference ('SESSION_IP_ADDRESS' => &null
) immediately after the session starts. What is going on?!
To reiterate, this is the output the first time:
array(0) {
}
array(1) {
["SESSION_IP_ADDRESS"]=>
string(11) "xx.xx.xxx.x"
}
This is the output the second time:
array(1) {
["SESSION_IP_ADDRESS"]=>
&string(11) "xx.xx.xxx.x"
}
array(1) {
["SESSION_IP_ADDRESS"]=>
&string(11) "xx.xx.xxx.x"
}
And the third time and every time from then on:
array(1) {
["SESSION_IP_ADDRESS"]=>
&NULL
}
array(1) {
["SESSION_IP_ADDRESS"]=>
&string(11) "xx.xx.xxx.x"
}