Expecting variable to still exist after session_unset()
Confusing session_unset() with session_destroy()
4. Identify the error in the following code snippet that aims to destroy a session:
session_unset();
session_destroy();
medium
A. No error, code works fine
B. Missing session_start() before unsetting and destroying
C. session_unset() does not clear session variables
D. session_destroy() should be called before session_unset()
Solution
Step 1: Check session lifecycle requirements
Before accessing or modifying session data, session_start() must be called to initialize the session.
Step 2: Analyze the given code
The code calls session_unset() and session_destroy() without starting the session, which causes errors or unexpected behavior.
Final Answer:
Missing session_start() before unsetting and destroying -> Option B
Quick Check:
Always start session before unsetting/destroying [OK]
Hint: Always call session_start() before session_unset() or session_destroy() [OK]
Common Mistakes:
Forgetting to call session_start() first
Calling session_destroy() before session_unset() (not an error but unusual)
Assuming session_unset() destroys session
5. You want to completely log out a user by destroying the session and removing the session cookie. Which of the following code snippets correctly achieves this?
hard
A. session_start(); session_unset(); session_destroy(); setcookie(session_name(), '', time() - 3600);
B. session_destroy(); session_unset(); setcookie(session_name(), '', time() + 3600);
C. session_start(); session_destroy(); setcookie(session_name(), '', time() + 3600);
D. session_unset(); session_start(); setcookie(session_name(), '', time() - 3600);
Solution
Step 1: Start the session to access session data
Call session_start() to initialize the session before modifying it.
Step 2: Clear session variables and destroy session
Use session_unset() to clear variables, then session_destroy() to end the session.
Step 3: Remove the session cookie from the client
Call setcookie() with the session name and a past expiration time to delete the cookie.