proper way to logout from a session in PHP

后端 未结 4 1974
误落风尘
误落风尘 2020-11-28 09:00

I have read many php tutorials for logout scripts, i am wondering what could be the proper way to logout from a session!

Script 1



        
相关标签:
4条回答
  • 2020-11-28 09:41
    <?php
    // Initialize the session.
    session_start();
    // Unset all of the session variables.
    unset($_SESSION['username']);
    // Finally, destroy the session.    
    session_destroy();
    
    // Include URL for Login page to login again.
    header("Location: login.php");
    exit;
    ?>
    
    0 讨论(0)
  • 2020-11-28 09:47

    Personally, I do the following:

    session_start();
    setcookie(session_name(), '', 100);
    session_unset();
    session_destroy();
    $_SESSION = array();
    

    That way, it kills the cookie, destroys all data stored internally, and destroys the current instance of the session information (which is ignored by session_destroy).

    0 讨论(0)
  • 2020-11-28 09:52

    Session_unset(); only destroys the session variables. To end the session there is another function called session_destroy(); which also destroys the session .

    update :

    In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that

    0 讨论(0)
  • 2020-11-28 09:56

    From the session_destroy() page in the PHP manual:

    <?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();
    ?>
    
    0 讨论(0)
提交回复
热议问题