Consider the following PHP code that starts a session, sets a variable, destroys the session, and then tries to access the variable. What will be the output?
<?php session_start(); $_SESSION['user'] = 'Alice'; session_destroy(); echo isset($_SESSION['user']) ? $_SESSION['user'] : 'No user'; ?>
Think about what happens to session variables after session_destroy() is called.
Calling session_destroy() ends the session and clears session data on the server, but the $_SESSION superglobal in the current script is not automatically cleared. Therefore, isset($_SESSION['user']) returns true, and 'Alice' is printed.
What will this PHP code output?
<?php session_start(); $_SESSION['count'] = 5; unset($_SESSION['count']); echo isset($_SESSION['count']) ? $_SESSION['count'] : 'Count not set'; ?>
What does unset() do to the session variable?
Using unset() on a session variable removes it from the $_SESSION array. So after unsetting, $_SESSION['count'] no longer exists, and the isset() check returns false, printing 'Count not set'.
Look at this PHP code snippet intended to destroy a session. Why does it fail to fully destroy the session?
<?php session_start(); $_SESSION['logged_in'] = true; session_destroy(); echo isset($_SESSION['logged_in']) ? 'Still logged in' : 'Logged out'; ?>
Check what session_destroy() does and what it does not do.
session_destroy() removes the session data stored on the server but does not clear the $_SESSION array in the current script. So the variable $_SESSION['logged_in'] still exists in the script's memory until manually cleared or the script ends.
Which of the following PHP code snippets correctly destroys the session and clears all session variables?
Remember the order: you must start the session before modifying or destroying it.
You must call session_start() first to access the session. Then clear $_SESSION array to remove variables, and finally call session_destroy() to remove session data on the server. Option A follows this order correctly.
Given this PHP code, how many session variables remain in $_SESSION after execution?
<?php session_start(); $_SESSION['a'] = 1; $_SESSION['b'] = 2; $_SESSION['c'] = 3; unset($_SESSION['b']); session_destroy(); ?>
Consider what unset() and session_destroy() do to $_SESSION in the current script.
unset($_SESSION['b']) removes the 'b' variable, so only 'a' and 'c' remain in the $_SESSION array. session_destroy() deletes the session data on the server but does not clear the $_SESSION array in the current script. So after execution, $_SESSION still contains 2 variables: 'a' and 'c'.