PHP Sessions

Sessions are small, temporary files that are stored on the website's server. Sessions can be used to store unique information about, or change unique settings for each visitor, but only for the duration of each separate visit.

Sessions work by assigning each visitor a unique string that is used to identify them as they move from page to page. This prevents one visitor's information from being mixed up with another's.

PHP allows you to create and destroy a session, as well as assign, retrieve and update session variables. The session_start() function is used to first create a session, or to continue the current session if one already exists. This function must be run on every page, before any other data is sent to the browser, such as the opening <html> tag or random whitespace. The code is very simple.

<?php
  session_start();
?>

After starting the session you can store session variables in the $_SESSION superglobal, as well as update and retrieve them. Each value stored in this array is assigned a "key" or name by which to identify the specific value. The syntax is: $_SESSION['key'] = value;

<?php
  session_start();

  $_SESSION['question'] = 'What happens when you throw a green stone in the red sea?';

  $_SESSION['answer'] = 'It gets wet!';
?>

Due to the nature of sessions, you can assign a session value on one page and retrieve it on a completely separate page, as long as session_start() is set at the beginning of the file. The best practice is to check and see if each session value exists before retrieving it, by using the isset() function.

<?php
  session_start();

  if (isset($_SESSION['question']) && isset($_SESSION['answer'])) {
    echo $_SESSION['question'];
    echo $_SESSION['answer'];
  }
?>

Although sessions will end themselves and erase all session variables after a period of inactivity, it is possible to speed up the process. This is necessary if you are using sessions to keep a person logged into a website, for example, and they click "logout". The unset() function will free (erase) a specific session variable, and the session_destroy() function will end the session completely, as well as erase all session variables.

<?php
  unset($_SESSION['question']);
  unset($_SESSION['answer']);
  session_destroy();
?>