Normally web pages are blind to other web pages. Cookies allow you to pass information from one web page to another. Sessions are an alternative method. Cookies store the information on the visiter's computer. This has two problems. First of all, the visiter may have his browser set to reject cookies so if your script relies on cookies, it won't work for them. Secondly, since the cookie is on the is on the visiter's computer, it can be manipulated by the user and that can be a security risk. Sessions let you pass information from one web page to others when cookies are disabled.
When a visiter first comes to one of your session enabled pages, they are assigned a unique identifier.
If the
viewer has cookies enabled, that identifier is set as a cookie, if not, you can encode the identifier into the
links on the page or use it as a hidden variable in your forms. The identifier doesn't store information. The
information is stored on the server instead of the visiter's computer and the identifier tells where it is on
the server. The identifier assigned to you is e4ca99ed7dacd6fe9f49e4657f0451aa. The way I show it is
<?php echo session_id(); ?>. If the viewer's browser is set to reject cookies, PHP
has ways to add the identifier to URL's and forms.
To enable sessions on a web page, use the session_start() function. Because this attempts
to set
the identifier as a cookie, it must be called before any output is sent to the browse. That means no HTML, no
text and no image. Not even a space. Since there is no expiry time set, the cookie with the identifier is
deleted when the browser is shut down. If you want to close the session before the browser would on is own,
use session_destroy(). That will erase all session variables. It does not do so instantly however.
The session variables remain accessable to the script that destroyed them until the web page is reloaded. You
can also delete every variable in the session array by assigning an empty array to it:
<?
$_SESSION = array();
?>
Sessions are stored as an associative array called
$_SESSION and you can set them like any other variable. For example, if you have this form...
<form action="index.php#color_form">
<select name="color">
<option value="red">Red</option>
<option value="green"<?php if ( $_GET['color'] == "green")
{ echo " selected";} ?>>Green</option>
<option value="blue"<?php if ( $_GET['color'] == "blue")
{ echo " selected";} ?>>Blue</option>
</select>
<input type="submit">
</form>
... the PHP to set the session would be...
<?php
if ( isset($_GET['color']) )
{
$_SESSION['color'] = $_GET['color'];
echo $_SESSION['color'];
}
?>
Unsetting a single session variable is simple. Using the example above, we unset the color variable like so:
<?php
unset($_SESSION['color']);
?>