Jochem Jochem - 3 months ago 8
PHP Question

How do I properly unset a $_SESSION variable?

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.

Answer

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.