Skip to content
Home » Web » PHP » session_destroy vs session_unset

session_destroy vs session_unset

session_destroy

A simple test can show you that session_destroy() does not destroy session variables.

<?php
session_start();
$_SESSION['timezone'] = "America/New_York";
echo "Session ID before destroy: " . session_id() . "<br />";
echo "Session Timezone: " . $_SESSION['timezone'] . "<br />";
echo "<br />";

session_destroy();
echo "Session ID after destroy: " . session_id() . "<br />";
echo "Session Timezone: " . $_SESSION['timezone'] . "<br />";
echo "<br />";
?>

The result is:

Session ID before destroy: ghm311t10lc47m210n2j7qph27
Session Timezone: America/New_York

Session ID after destroy:
Session Timezone: America/New_York

session_unset

As you can see, session_destroy() did disassociate with the session id, but left session variables unchanged. If you want a more meaningful destroy, just simply use session_unset() to unset all variables of the session before session_destroy() like this:

<?php
session_start();
$_SESSION['timezone'] = "America/New_York";
echo "Session ID before destroy: " . session_id() . "<br />";
echo "Session Timezone: " . $_SESSION['timezone'] . "<br />";
echo "<br />";

session_unset();
session_destroy();
echo "Session ID after destroy: " . session_id() . "<br />";
echo "Session Timezone: " . $_SESSION['timezone'] . "<br />";
echo "<br />";
?>

The result is:

Session ID before destroy: ghm311t10lc47m210n2j7qph27
Session Timezone: America/New_York

Session ID after destroy:

Notice: Undefined index: timezone in /var/www/html/test.php on line 11
Session Timezone:

The last error is the exact evident of the session being destroyed. This should be a more meaningful way to clear a session.

Leave a Reply

Your email address will not be published. Required fields are marked *