PHP
unset() and session_destroy()
Learn to remove a single session variable with unset() and destroy the whole session with session_destroy().
unset() removes a single variable
To remove a single session variable, use unset($_SESSION['key']). This removes only that key; the rest of the session stays.
For example, to drop one product from a cart, write unset($_SESSION['cart'][$productId]). The whole cart remains.
Note: unset($_SESSION) destroys the whole superglobal but does not close the session. To close it, use session_destroy().
session_destroy() closes the whole session
session_destroy() wipes all session data on the server. The session file is deleted; the next session_start() begins a fresh session.
In a logout flow, first remove the user variable with unset($_SESSION['user']), then close the session with session_destroy().
The cookie may linger in the browser; you can also delete it after session_destroy(). For a basic flow, destroy is enough.
Exercise Remove the cart key and check it
Call session_start(). Set $_SESSION['cart'] = 3. Then remove it with unset($_SESSION['cart']). With if/else, check isset($_SESSION['cart']): if defined print yes, otherwise gone.
Show example solution
Call session_start, set $_SESSION['cart']=3, call unset($_SESSION['cart']), then if(isset(...)) prints yes/gone.
Example solution:
<?php
// Remove $_SESSION['cart'] with unset and check with isset
session_start();
$_SESSION['cart'] = 3;
unset($_SESSION['cart']);
if (isset($_SESSION['cart'])) {
echo "yes\n";
} else {
echo "gone\n";
}
Test yourself
-
What does session_destroy() do?
- Removes a single variable
- Empties $_SESSION but keeps the session open
- Only deletes the cookie
- Destroys all session data on the server
Show answer
Destroys all session data on the server — Correct. session_destroy() destroys the session data on the server.
-
Remove a single key
<?php
session_start();
$_SESSION['cart'] = ['id' => 7, 'qty' => 3];
____
var_dump(isset($_SESSION['cart']));
Show answer
<?php
session_start();
$_SESSION['cart'] = ['id' => 7, 'qty' => 3];
unset($_SESSION['cart']);
var_dump(isset($_SESSION['cart']));
-
Match the cleanup tools
- unset($_SESSION['k'])
- Removes one key
- session_destroy()
- Destroys the whole session
- session_unset()
- Removes all keys
- session_id()
- Reads the id
Next lesson: Login/logout logic