[ Team LiB ] Previous Section Next Section

Destroying Sessions and Unsetting Elements

You can use session_destroy() to end a session, erasing all session variables. session_destroy() requires no arguments. You should have an established session for this function to work as expected. The following code fragment resumes a session and abruptly destroys it:


session_start();
session_destroy();

When you move on to other pages that work with a session, the session you have destroyed will not be available to them, forcing them to initiate new sessions of their own. Any variables that have been registered will have been lost.

However, session_destroy() does not instantly destroy elements of the $_SESSION array. These remain accessible to the script in which session_destroy() is called (until it is reloaded). The following code fragment resumes or initiates a session and registers a session element called test, which we set to 5. Destroying the session does not destroy the registered variable:


session_start();
$_SESSION['test'] = 5;
session_destroy();
print $_SESSION['test']; // prints 5

To remove all $_SESSION elements, you should simply assign an empty array to the variable, like so:


session_start();
$_SESSION['test'] = 5;
session_destroy();
$_SESSION=array();
print $_SESSION['test']; // prints nothing. The test element is no more

You can remove individual elements by calling unset() on them, like so:


unset( $_SESSION['test'] );


    [ Team LiB ] Previous Section Next Section