Destroying Sessions and Unsetting Variables


You can use session_destroy() to end a session, erasing all session variables. The session_destroy() function 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 registered variables will be lost.

The session_destroy() function does not instantly destroy registered variables, however. They 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 variable called test, which we set to 5. Destroying the session does not destroy the registered variable.

session_start(); $_SESSION["test"] = 5; session_destroy(); echo $_SESSION["test"]; // prints 5


To remove all registered variables from a session, you simply unset the variable:

session_start(); $_SESSION["test"] = 5; session_destroy(); unset($_SESSION["test"]); echo $_SESSION["test"]; // prints nothing.





Sams Teach Yourself PHP, MySQL And Apache All in One
Sams Teach Yourself PHP, MySQL and Apache All in One (3rd Edition)
ISBN: 0672328739
EAN: 2147483647
Year: 2004
Pages: 327

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net