LVII. Session handling functions

Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.

If you are familiar with the session management of PHPLIB, you will notice that some concepts are similar to PHP's session support.

A visitor accessing your web site is assigned an unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.

The session support allows you to register arbitrary numbers of variables to be preserved across requests. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start() or implicitly through session_register()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.

All registered variables are serialized after the request finishes. Registered variables which are undefined are marked as being not defined. On subsequent accesses, these are not defined by the session module unless the user defines them later.

track_vars and register_globals configuration settings influence how the session variables get stored and restored.

If track_vars is enabled and register_globals is disabled, only members of the global associative array $HTTP_SESSION_VARS can be registered as session variables. The restored session variables will only be available in the array $HTTP_SESSION_VARS.

Example 1. Registering a variable with track_vars enabled


<?php
session_register("count");
$HTTP_SESSION_VARS["count"]++;
?>
     

If register_globals is enabled, then all global variables can be registered as session variables and the session variables will be restored to corresponding global variables.

Example 2. Registering a variable with register_globals enabled


<?php
session_register("count");
$count++;
?>
     

If both track_vars and register_globals are enabled, then the globals variables and the $HTTP_SESSION_VARS entries will reference the same value.

There are two methods to propagate a session id:

  • Cookies

  • URL parameter

The session module supports both methods. Cookies are optimal, but since they are not reliable (clients are not bound to accept them), we cannot rely on them. The second method embeds the session id directly into URLs.

PHP is capable of doing this transparently when compiled with --enable-trans-sid. If you enable this option, relative URIs will be changed to contain the session id automatically. Alternatively, you can use the constant SID which is defined, if the client did not send the appropriate cookie. SID is either of the form session_name=session_id or is an empty string.

The following example demonstrates how to register a variable, and how to link correctly to another page using SID.

Example 3. Counting the number of hits of a single user


<?php
session_register ("count");
$count++;
?>

Hello visitor, you have seen this page <? echo $count; ?> times.<p>

<php?
# the <?=SID?> is necessary to preserve the session id
# in the case that the user has disabled cookies
?>

To continue, <A HREF="nextpage.php?<?=SID?>">click here</A>
     

To implement database storage you need PHP code and a user level function session_set_save_handler(). You would have to extend the following functions to cover MySQL or another database.

Example 4. Usage of session_set_save_handler()


<?php

function open ($save_path, $session_name) {
    echo "open ($save_path, $session_name)\n";
    return true;
}

function close() {
    echo "close\n";
    return true;
}

function read ($key) {
    echo "read ($key)\n";
    return "foo|i:1;";
}

function write ($key, $val) {
    echo "write ($key, $val)\n";
    return true;
}

function destroy ($key) {
    return true;
}

function gc ($maxlifetime) {
    return true;
}

session_set_save_handler ("open", "close", "read", "write", "destroy", "gc");

session_start();

$foo++;

?>
     

Will produce this results:


$ ./php save_handler.php
Content-Type: text/html
Set-cookie: PHPSESSID=f08b925af0ecb52bdd2de97d95cdbe6b

open (/tmp, PHPSESSID)
read (f08b925af0ecb52bdd2de97d95cdbe6b)
write (f08b925af0ecb52bdd2de97d95cdbe6b, foo|i:2;)
close
    

The <?=SID?> is not necessary, if --enable-trans-sid was used to compile PHP.

The session management system supports a number of configuration options which you can place in your php.ini file. We will give a short overview.

  • session.save_handler defines the name of the handler which is used for storing and retrieving data associated with a session. Defaults to files.

  • session.save_path defines the argument which is passed to the save handler. If you choose the default files handler, this is the path where the files are created. Defaults to /tmp.

  • session.name specifies the name of the session which is used as cookie name. It should only contain alphanumeric characters. Defaults to PHPSESSID.

  • session.auto_start specifies whether the session module starts a session automatically on request startup. Defaults to 0 (disabled).

  • session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means "until the browser is closed." Defaults to 0.

  • session.serialize_handler defines the name of the handler which is used to serialize/deserialize data. Currently, a PHP internal format (name php) and WDDX is supported (name wddx). WDDX is only available, if PHP is compiled with WDDX support. Defaults to php.

  • session.gc_probability specifies the probability that the gc (garbage collection) routine is started on each request in percent. Defaults to 1.

  • session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and cleaned up.

  • session.referer_check contains the substring you want to check each HTTP Referer for. If the Referer was sent by the client and the substring was not found, the embedded session id will be marked as invalid. Defaults to the empty string.

  • session.entropy_file gives a path to an external resource (file) which will be used as an additional entropy source in the session id creation process. Examples are /dev/random or /dev/urandom which are available on many Unix systems.

  • session.entropy_length specifies the number of bytes which will be read from the file specified above. Defaults to 0 (disabled).

  • session.use_cookies specifies whether the module will use cookies to store the session id on the client side. Defaults to 1 (enabled).

  • session.cookie_path specifies path to set in session_cookie. Defaults to /.

  • session.cookie_domain specifies domain to set in session_cookie. Default is none at all.

  • session.cache_limiter specifies cache control method to use for session pages (nocache/private/public). Defaults to nocache.

  • session.cache_expire specifies time-to-live for cached session pages in minutes, this has no effect for nocache limiter. Defaults to 180.

Note: Session handling was added in PHP 4.0.

Table of Contents
session_start — Initialize session data
session_destroy — Destroys all data registered to a session
session_name — Get and/or set the current session name
session_module_name — Get and/or set the current session module
session_save_path — Get and/or set the current session save path
session_id — Get and/or set the current session id
session_register — Register one or more variables with the current session
session_unregister — Unregister a variable from the current session
session_unset — Free all session variables
session_is_registered — Find out if a variable is registered in a session
session_get_cookie_params — Get the session cookie parameters
session_set_cookie_params — Set the session cookie parameters
session_decode — Decodes session data from a string
session_encode — Encodes the current session data as a string

Hosted by Tonec Inc.