Reading and Writing Sessions

  echo 'Sessions activated.<br />';
  $_SESSION['version'] = phpversion();
  echo 'Session data written.<br />';
  echo "Session data read: {$_SESSION['version']}.";

All session data is accessible from a PHP script via the $_SESSION array. Because the data itself is stored on the server-side, you can write session data and read it in the next PHP statement, without the requirement of a round-trip to the server as it was with cookies. Just remember to call session_start() first and then access $_SESSION. The preceding listing creates a session file that figure shows.

The content of the session file created by Listing

Closing Sessions

In some instances, for example when a user logs out, all session data should be removed, and the session must be closed. Of course, it would be possible to loop through $_SESSION with foreach and then set each value to an empty string or null, but there is a quicker way: Call session_destroy(). After that, all data in the current session is destroyed, as the function name suggests.

session_destroy() function

bool session_destroy ( void )

session_destroy destroys all of the data associated with the current session and returns TRUE on success or FALSE on failure.

Removing All Session Data

  echo 'Before: <pre>';
  echo '</pre>After: <pre> ';
  echo '</pre>';

by BrainBellupdated