Sessions in PHP

NB: When you use sessions the code session_start(); must be put at the start of every page.

To create a session in PHP you simply assign a (key, value) pair to the $_SESSION array.

$_SESSION[$name] = $value;

To read a value from a session you use the $_SESSION array.

if ($_SESSION[$name] == $value)
   echo 'You are logged in.';
else
   echo 'You are not logged in.';

This example checks to see if a session has a certain value and prints a message depending on whether the session has the correct value.

setcookie($name, '', time()-100000);
unset($_SESSION[$name]);
session_destroy();

To delete a session you firstly need to delete the associated cookie (the cookie has the same name as the session) and then delete the entry in the array.

session_unset();

The code above deletes all sessions that are active.

Downloads

Categories

Tags

No tags

Social