Note that there are some explanatory texts on larger screens.

plurals
  1. POClose session and start a new one
    text
    copied!<p>I'm testing the implementation of a security check in my PHP sessions. I can successfuly detect whether the session was started from another IP address and I can successfully start a new session. However, the data from the old session gets copied into the new one! How can I start a blank session while preserving the previous session data for its legitimate owner?</p> <p>This is my code so far, after lots of failed attempts:</p> <pre><code>&lt;?php // Security check if( isset($_SESSION['ip_address']) &amp;&amp; $_SERVER['REMOTE_ADDR']!=$_SESSION['ip_address'] ){ // Check failed: we'll start a brand new session session_regenerate_id(FALSE); $tmp = session_id(); session_write_close(); unset($_SESSION); session_id($tmp); session_start(); } // First time here if( !isset($_SESSION['ip_address']) ){ $_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR']; $_SESSION['start_date'] = new DateTime; } </code></pre> <p>The official documentation about sessions is terribly confusing :(</p> <p><strong>Update:</strong> I'm posting some findings I got through trial and error. They seem to work:</p> <pre><code>&lt;?php // Load the session that we will eventually discard session_start(); // We can only generate a new ID from an open session session_regenerate_id(); // We store the ID because it gets lost when closing the session $tmp = session_id(); // Close session (doesn't destroy data: $_SESSION and file remains) session_destroy(); // Set new ID for the next session session_id($tmp); unset($tmp); // Start session (uses new ID, removes values from $_SESSION and loads the new ones if applicable) session_start(); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload