Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

php - Close session and start a new one

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...