Saving State with Sessions

Using PHP sessions you can avoid managing generation of session ID's and saving values at the server. The basic steps are

  1. Starting the session
  2. Register session variables
  3. Do your business in the session (using the variables)
  4. Deregister session variables
  5. Stop (Destroy) the session
A nice security feature of session variables is, that they cannot be overridden by GET and POST data (i.e. using parameters).

However, they might be set by GET and POST data, if they are not set already. Use the function session_is_registered("pass") instead of isset("pass").

The behaviour of PHP-sessions depends on a number of parameter settings in the configuration of PHP (defined in the php.ini file).

As usual, you can see the values by calling phpinfo();

Session options briefly

session.name: This is the name used as cookie/parameter name.

session.cookie_lifetime: Lifetime of cookie in seconds. Value 0 (default) means until browser (all windows) is closed.

session.use_cookies: Whether to user cookies or URL parameters.

register_globals: If "On" you can register all global variables, and access the variables as usual, as in the example above.
If "Off", you can only use entries of the associative array $HTTP_SESSION_VARS (or $_SESSION from PHP 4.1.0) as session variables, e.g. $HTTP_SESSION_VARS["pass"]. These variables do not need to be registered and unregistered.

session.use_trans_sid: If true (1) the session Id is embedded automatically in the local URLs.

session.save_handler: Default set to "files". You can implement your own handler methods, e.g. to use a database - useful if sessions should work cross several web-servers.

You can change many of the configuration parameters for the duration of a script using the ini_set() function. The session parameters can also be changed using specialised functions, e.g. session_set_cookie_params(int lifetime [, string path [, string domain [, bool secure])