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
113 views
in Technique[技术] by (71.8m points)

Truly destroying a PHP Session?

I have heard mixed responses on this topic, so what is a sure fire way to destroy a PHP session?

session_start();
if(isset($_SESSION['foo'])) {
   unset($_SESSION['foo'];
   ...
}
session_destroy();

In the most simple of cases, would this sufficient to truly terminate the session between the user and the server?

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

To destroy a session you should take the following steps:

  • delete the session data
  • invalidate the session ID

To do this, I’d use this:

session_start();
// resets the session data for the rest of the runtime
$_SESSION = array();
// sends as Set-Cookie to invalidate the session cookie
if (isset($_COOKIE[session_name()])) { 
    $params = session_get_cookie_params();
    setcookie(session_name(), '', 1, $params['path'], $params['domain'], $params['secure'], isset($params['httponly']));
}
session_destroy();

And to be sure that the session ID is invalid, you should only allow session IDs that were being initiated by your script. So set a flag and check if it is set:

session_start();
if (!isset($_SESSION['CREATED'])) {
    // invalidate old session data and ID
    session_regenerate_id(true);
    $_SESSION['CREATED'] = time();
}

Additionally, you can use this timestamp to swap the session ID periodically to reduce its lifetime:

if (time() - $_SESSION['CREATED'] > ini_get('session.gc_maxlifetime')) {
    session_regenerate_id(true);
    $_SESSION['CREATED'] = time();
}

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

...