Destroying Sessions and Session Variables
April 29, 2002
To end a session, and destroy all session variables, use the
function: session_destroy(). The next page you go to will
no longer have access to the session variables. The variables will
still be available in the script where you called
session_destroy(). To remove all the session_variables
immediately, use the the function session_unset().
Individual session variables can either be unset with
unset() (for $_SESSION["varname"]), or by calling the
function session_unset() if you used
session_register() to set the variable.
Look at this example:
page8.php
<?php
session_start();
$_SESSION["firstname"] = "TimeIsUp";
session_destroy();
?>
Click here to <a href="page9.php?<?=SID?>">Forget the name</a>
page9.php
<?php
session_start();
print "Your firstname is: ".$_SESSION["firstname"]." ,or is it?";
?>
The firstname does not appear, as page8.php called
session_destroy(). However, if we moved
session_destroy() to page9.php, the variables would still
be available in that page, as follows:
page10.php
<?php
session_start();
$_SESSION["firstname"] = "IsTimeUp?";
?>
Click here to <a href="page11.php?<?=SID?>">try forget the name</a>
page11.php
<?php
session_start();
session_destroy();
print "Your firstname is: ".$_SESSION["firstname"];
?>
This time the name is remembered. However, click refresh once
on page11.php, and the firstname will disappear, as the session
was destroyed the first time you loaded page11.php. To see
session_unset() in action, we take the identical 2 scripts,
except that page13.php calls session_unset() immediately
before it calls session_destroy(), clearing
the session variables.
page 12.php
<?php
session_start();
$_SESSION["firstname"] = "TimeIsUp";
?>
Click here to <a href="page13.php?<?=SID?>">forget the name</a>
page13.php
<?php
session_start();
session_unset();
session_destroy();
print "Your firstname is: ".$_SESSION["firstname"];
?>
We could also replace session_unset() with unset (or
session_unregister(firstname) if
you're using session_register), and achieve
the same effect. session_unset() clears all the session
variables, session_unregister() just what is passed to
the function. Since we only have the one variable, the effect is
the same, as you would discover if you run the following script
in the same way, clicking from page12.php.
page13_2.php
<?php
session_start();
session_start();
unset($_SESSION["firstname"]);
// if you're using session_register, the function to call is:
// session_unregister(firstname);
session_destroy();
print "Your firstname is: $firstname";
?>
Session Variables
Maintaining state with PHP4 sessions
Encoding session variables
|