Quick reference: PHP sessions

Quick reference: PHP sessions

Starting, and continuing a session
On every PHP page you want to take use of sessions, start the script by calling session_start().

Registering session data
This is done by using the global $_SESSION array. Like this: $_SESSION['MyAge'] = ‘26′;

Closing and terminating all session data

$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
  setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();

Additional info
All session data is stored server-side, with only a cookie on the client-side telling the server what session-id it should work with. If the client browser has high security and you are afraid that cookies might not be available, then you can add the constant SID to every hyperlink necessary in order to pass the session-id around. This constant will not have any value unless the cookie creation fails.

A simple SID usage example

<a href="index.php?<?=SID?>">A link during a session that needs to have the session-id on the next page.</a>

If SID has a value, it would contain both the needed GET variable, and the session-id value. E.g. PHPSESSID=somevalue.

Get more information about php sessions over at php.net

Leave a Reply