开发者

How can I expire a user's session in PHP?

Some people say use unset($_SESSION["..."]) and some say session_unset() and some say $_SESSION = array() and some say session_destroy() and I am saying "for God's sake, this stuff开发者_StackOverflow is getting confusing, can someone please explain me which is the correct/secure way to log the user out" and what is used for what?

Appreciated...


<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
    $params["path"], $params["domain"],
    $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
?>

RTM


Here is the difference between the entities

you can remove a single variable in the session

 unset($_SESSION['shape']);

this would remove all the variables in the session, but not the session itself

 session_unset();

this would destroy the session variables

 session_destroy();


First of all, session_destroy() is not the same as the other methods. This one will destroy the current session data on the server, but will not unset any of the variables. It's simply the counterpart to session_start().

session_unset() is the deprecated equivalent to doing $_SESSION = array(). The latter and unset($_SESSION["..."]) are different only in the fact that the unset() route will only unset a single session variable, the one named in [...]. Never do unset($_SESSION), as that will interfere with the session mechanism itself.

Old question reference.


The only ones saying session_unset() are the ones stuck on obsolete versions of PHP - the function's been deprecated for a LONG time now.

The exact answer to this question depends on exactly what your code uses to determine if someone is "logged in" v.s. someone who is "logged out".

If you have a single $_SESSION['logged_in'] = true that your code looks for, then why unset it? Just set it to false and boom... user is logged out.


session_destroy — Destroys all data registered to a session
session_unset — Free all session variables

http://www.php.net/manual/en/book.session.php

The most I've seen used is to call them in this order.

session_unset();
session_destroy();
$_SESSION = array();


if you use session_destroy() then the cookie in the browser is also cleard (and probbley a new session gets created later)

personaly i use an object(s) to track different things (like public loggedIn = False; and a function witch actally logs the user in)

session_unset() is handy if you want to keep the coockie, but you will end up with more empty sessions in the server

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜