Tuesday, April 20, 2010

Workshop 7 PHP Sessions

Sessions

Sessions are unique identifier of a user, which can be used to store and retrieve information attached to the user. Therefore enabling the website to know what the user have seen, browse through etc. The user would need to have cookies enabled for session to work.

1. Initializing a session

<?php
session_start();

echo "<p>Your session ID is ".session_id()."</p>";
?>

Your session id stays the same all the time.

2. Storing and accessing session variables
We'll store the variables first in a separate file

<?php
session_start();

$_SESSION[product1] = "Sonic Screwdriver";
$_SESSION[product2] = "HAL 2000";
echo "The products have been registered.";

?>


Once you have executed this script, run the next script. The above script will attached the data onto session variables.

<?php
session_start();

echo "Your chosen products are:";
echo "<ul><li>$_SESSION[product1] <li>$_SESSION[product2]\n</ul>\n";
?>


3. Destroying sessions and variables. Once executed it would remove the session and the corresponding variables

<?php 
session_start();
session_destroy(); 
unset($session[product1]); // Remove product 1 
unset($session[product2]); // Remove product 2 

// This should print nothing 
echo "Your chosen products are:";
echo "<ul><li>$_SESSION[product1] <li>$_SESSION[product2]\n</ul>\n";
?>

0 comments:

Post a Comment