如何正确取消设置$ _SESSION变量?

如何正确取消设置$ _SESSION变量?

问题描述:

Part of the login script that sets the $_SESSION:

session_start();
$_SESSION['username'] = '$myuser';
header("location: loggedinonly.php");

The logout page:

<!DOCTYPE html>

<?php
    session_start;
    unset($_SESSION['username']);
    header('location: /phptest');
?>

The page you should only see when logged in:

<!DOCTYPE html>

<?php
    session_start();
    if (!isset($_SESSION['username'])) {
        print("NO ACCESS");
    } else {
        print("WELCOME");
    }
?>
<html>
    <head>
        <title>LOGIN PAGE</title>
        <link rel="stylesheet" type="text/css" href="stylesheet.css">
    </head>
    <body>
        You must be logged in to read this!<br>
    </body>
</html>

When I open a new session, I do not have access. But if I log in, then go to the page, I do have access. All of this is intended. However, when I logout via the script, I still have access.

I've tried a lot, sorry if this has been asked before, I found nothing useful via the search.

You are using unset on a single session variable so you still might have something keeping the user logged in. Try with session_destroy() and it will remove all data associated with the session.

The logout page:

<?php
if(isset($_SESSION['username'])){
session_start();
session_destroy();
session_commit();
header('Location: phptest.php');
}
?>