Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close session and start a new one

Tags:

php

session

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?

This is my code so far, after lots of failed attempts:

<?php

// Security check
if( isset($_SESSION['ip_address']) && $_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;
}

The official documentation about sessions is terribly confusing :(

Update: I'm posting some findings I got through trial and error. They seem to work:

<?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();
like image 472
Álvaro González Avatar asked Dec 03 '10 11:12

Álvaro González


2 Answers

Just call session_unset after session_regenerate_id to reset $_SESSION for the current session:

if (isset($_SESSION['ip_address']) && $_SERVER['REMOTE_ADDR']!=$_SESSION['ip_address']) {
    // Check failed: we'll start a brand new session
    session_regenerate_id(FALSE);
    session_unset();
}
like image 157
Gumbo Avatar answered Oct 30 '22 02:10

Gumbo


when a new user connects to your server, the script should only be able to access that user's session variables. you will want to store other info in a hashed session variable to verify that the session is not being jacked. if it is being jacked, no reason to start a new session, maybe just exit the script with a warning.

here is the function a lot of people use for fingerprinting a session:

function fingerprint() {
    $fingerprint = $server_secure_word;
    $fingerprint .= $_SERVER['HTTP_USER_AGENT'];
    $blocks = explode('.', $_SERVER['REMOTE_ADDR']);
    for ($i=0; $i<$ip_blocks; $i++) {
        $fingerprint .= $blocks[$i] . '.';
    }
    return md5($fingerprint);
}
like image 25
dqhendricks Avatar answered Oct 30 '22 02:10

dqhendricks