CXLII. Session Handling Functions

Introduction

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.

A visitor accessing your web site is assigned a 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.

Caution

If you do turn on session.auto_start then you cannot put objects into your sessions since the class definition has to be loaded before starting the session in order to recreate the objects in your session.

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.

Warning

Some types of data can not be serialized thus stored in sessions. It includes resource variables or objects with circular references (i.e. objects which passes a reference to itself to another object).

Note: Session handling was added in PHP 4.0.

Note: Please note when working with sessions that a record of a session is not created until a variable has been registered using the session_register() function or by adding a new key to the $_SESSION superglobal array. This holds true regardless of if a session has been started using the session_start() function.

Sessions and security

External links: Session fixation

The session module cannot guarantee that the information you store in a session is only viewed by the user who created the session. You need to take additional measures to actively protect the integrity of the session, depending on the value associated with it.

Assess the importance of the data carried by your sessions and deploy additional protections -- this usually comes at a price, reduced convenience for the user. For example, if you want to protect users from simple social engineering tactics, you need to enable session.use_only_cookies. In that case, cookies must be enabled unconditionally on the user side, or sessions will not work.

There are several ways to leak an existing session id to third parties. A leaked session id enables the third party to access all resources which are associated with a specific id. First, URLs carrying session ids. If you link to an external site, the URL including the session id might be stored in the external site's referrer logs. Second, a more active attacker might listen to your network traffic. If it is not encrypted, session ids will flow in plain text over the network. The solution here is to implement SSL on your server and make it mandatory for users.

Requirements

No external libraries are needed to build this extension.

Note: Optionally you can use shared memory allocation (mm), developed by Ralf S. Engelschall, for session storage. You have to download mm and install it. This option is not available for Windows platforms. Note that the session storage module for mm does not guarantee that concurrent accesses to the same session are properly locked. It might be more appropriate to use a shared memory based filesystem (such as tmpfs on Solaris/Linux, or /dev/md on BSD) to store sessions in files, because they are properly locked. Session data is stored in memory thus web server restart deletes it.

Installation

Session support is enabled in PHP by default. If you would not like to build your PHP with session support, you should specify the --disable-session option to configure. To use shared memory allocation (mm) for session storage configure PHP --with-mm[=DIR] .

The windows version of PHP has built in support for this extension. You do not need to load any additional extension in order to use these functions.

Note: By default, all data related to a particular session will be stored in a file in the directory specified by the session.save_path INI option. A file for each session (regardless of if any data is associated with that session) will be created. This is due to the fact that a session is opened (a file is created) but no data is even written to that file. Note that this behavior is a side-effect of the limitations of working with the file system and it is possible that a custom session handler (such as one which uses a database) does not keep track of sessions which store no data.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Session configuration options

NameDefaultChangeableChangelog
session.save_path""PHP_INI_ALL 
session.name"PHPSESSID"PHP_INI_ALL 
session.save_handler"files"PHP_INI_ALL 
session.auto_start"0"PHP_INI_ALL 
session.gc_probability"1"PHP_INI_ALL 
session.gc_divisor"100"PHP_INI_ALLAvailable since PHP 4.3.2.
session.gc_maxlifetime"1440"PHP_INI_ALL 
session.serialize_handler"php"PHP_INI_ALL 
session.cookie_lifetime"0"PHP_INI_ALL 
session.cookie_path"/"PHP_INI_ALL 
session.cookie_domain""PHP_INI_ALL 
session.cookie_secure""PHP_INI_ALLAvailable since PHP 4.0.4.
session.cookie_httponly""PHP_INI_ALLAvailable since PHP 5.2.0.
session.use_cookies"1"PHP_INI_ALL 
session.use_only_cookies"1"PHP_INI_ALLAvailable since PHP 4.3.0.
session.referer_check""PHP_INI_ALL 
session.entropy_file""PHP_INI_ALL 
session.entropy_length"0"PHP_INI_ALL 
session.cache_limiter"nocache"PHP_INI_ALL 
session.cache_expire"180"PHP_INI_ALL 
session.use_trans_sid"0"PHP_INI_ALLPHP_INI_ALL in PHP <= 4.2.3. PHP_INI_PERDIR in PHP < 5. Available since PHP 4.0.3.
session.bug_compat_42"1"PHP_INI_ALLAvailable since PHP 4.3.0.
session.bug_compat_warn"1"PHP_INI_ALLAvailable since PHP 4.3.0.
session.hash_function"0"PHP_INI_ALLAvailable since PHP 5.0.0.
session.hash_bits_per_character"4"PHP_INI_ALLAvailable since PHP 5.0.0.
url_rewriter.tags"a=href,area=href,frame=src,form=,fieldset="PHP_INI_ALLAvailable since PHP 4.0.4.
For further details and definitions of the PHP_INI_* constants, see the Appendix G.

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 string

session.save_handler defines the name of the handler which is used for storing and retrieving data associated with a session. Defaults to files. See also session_set_save_handler().

session.save_path string

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. See also session_save_path().

There is an optional N argument to this directive that determines the number of directory levels your session files will be spread around in. For example, setting to '5;/tmp' may end up creating a session file and location like /tmp/4/b/1/e/3/sess_4b1e384ad74619bd212e236e52a5a174If . In order to use N you must create all of these directories before use. A small shell script exists in ext/session to do this, it's called mod_files.sh. Also note that if N is used and greater than 0 then automatic garbage collection will not be performed, see a copy of php.ini for further information. Also, if you use N, be sure to surround session.save_path in "quotes" because the separator (;) is also used for comments in php.ini.

Warning

If you leave this set to a world-readable directory, such as /tmp (the default), other users on the server may be able to hijack sessions by getting the list of files in that directory.

Note: Prior to PHP 4.3.6, Windows users had to change this variable in order to use PHP's session functions. A valid path must be specified, e.g.: c:/temp.

session.name string

session.name specifies the name of the session which is used as cookie name. It should only contain alphanumeric characters. Defaults to PHPSESSID. See also session_name().

session.auto_start boolean

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

session.serialize_handler string

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 are supported (name wddx). WDDX is only available, if PHP is compiled with WDDX support. Defaults to php.

session.gc_probability integer

session.gc_probability in conjunction with session.gc_divisor is used to manage probability that the gc (garbage collection) routine is started. Defaults to 1. See session.gc_divisor for details.

session.gc_divisor integer

session.gc_divisor coupled with session.gc_probability defines the probability that the gc (garbage collection) process is started on every session initialization. The probability is calculated by using gc_probability/gc_divisor, e.g. 1/100 means there is a 1% chance that the GC process starts on each request. session.gc_divisor defaults to 100.

session.gc_maxlifetime integer

session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and cleaned up. Garbage collection occurs during session start.

Note: If different scripts have different values of session.gc_maxlifetime but share the same place for storing the session data then the script with the minimum value will be cleaning the data. In this case, use this directive together with session.save_path.

Note: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won't have problems with filesystems where atime tracking is not available.

session.referer_check string

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 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 integer

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

session.use_cookies boolean

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

session.use_only_cookies boolean

session.use_only_cookies specifies whether the module will only use cookies to store the session id on the client side. Enabling this setting prevents attacks involved passing session ids in URLs. This setting was added in PHP 4.3.0.

session.cookie_lifetime integer

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. See also session_get_cookie_params() and session_set_cookie_params(). Since the cookie is returned by the browser, it is not prolonged to suffice the lifetime. It must be sent manually by setcookie().

session.cookie_path string

session.cookie_path specifies path to set in session_cookie. Defaults to /. See also session_get_cookie_params() and session_set_cookie_params().

session.cookie_domain string

session.cookie_domain specifies the domain to set in session_cookie. Default is none at all meaning the host name of the server which generated the cookie according to cookies specification. See also session_get_cookie_params() and session_set_cookie_params().

session.cookie_secure boolean

session.cookie_secure specifies whether cookies should only be sent over secure connections. Defaults to off. This setting was added in PHP 4.0.4. See also session_get_cookie_params() and session_set_cookie_params().

session.cookie_httponly boolean

Marks the cookie as accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers).

session.cache_limiter string

session.cache_limiter specifies cache control method to use for session pages (none/nocache/private/private_no_expire/public). Defaults to nocache. See also session_cache_limiter().

session.cache_expire integer

session.cache_expire specifies time-to-live for cached session pages in minutes, this has no effect for nocache limiter. Defaults to 180. See also session_cache_expire().

session.use_trans_sid boolean

session.use_trans_sid whether transparent sid support is enabled or not. Defaults to 0 (disabled).

Note: For PHP 4.1.2 or less, it is enabled by compiling with --enable-trans-sid. From PHP 4.2.0, trans-sid feature is always compiled.

URL based session management has additional security risks compared to cookie based session management. Users may send a URL that contains an active session ID to their friends by email or users may save a URL that contains a session ID to their bookmarks and access your site with the same session ID always, for example.

session.bug_compat_42 boolean

PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you to initialize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used, and if session.bug_compat_warn is also enabled. This feature/bug can be disabled by disabling this directive.

session.bug_compat_warn boolean

PHP versions 4.2.3 and lower have an undocumented feature/bug that allows you to initialize a session variable in the global scope, albeit register_globals is disabled. PHP 4.3.0 and later will warn you, if this feature is used by enabling both session.bug_compat_42 and session.bug_compat_warn.

session.hash_function integer

session.hash_function allows you to specify the hash algorithm used to generate the session IDs. '0' means MD5 (128 bits) and '1' means SHA-1 (160 bits).

Note: This was introduced in PHP 5.

session.hash_bits_per_character integer

session.hash_bits_per_character allows you to define how many bits are stored in each character when converting the binary hash data to something readable. The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ",").

Note: This was introduced in PHP 5.

url_rewriter.tags string

url_rewriter.tags specifies which HTML tags are rewritten to include session id if transparent sid support is enabled. Defaults to a=href,area=href,frame=src,input=src,form=fakeentry,fieldset=

Note: If you want XHTML conformity, remove the form entry and use the <fieldset> tags around your form fields.

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

Note: As of PHP 4.0.3, track_vars is always turned on.

Resource Types

This extension has no resource types defined.

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

SID (string)

Constant containing either the session name and session ID in the form of "name=ID" or empty string if session ID was set in an appropriate session cookie.

Examples

Note: As of PHP 4.1.0, $_SESSION is available as a global variable just like $_POST, $_GET, $_REQUEST and so on. Unlike $HTTP_SESSION_VARS, $_SESSION is always global. Therefore, you do not need to use the global keyword for $_SESSION. Please note that this documentation has been changed to use $_SESSION everywhere. You can substitute $HTTP_SESSION_VARS for $_SESSION, if you prefer the former. Also note that you must start your session using session_start() before use of $_SESSION becomes available.

The keys in the $_SESSION associative array are subject to the same limitations as regular variable names in PHP, i.e. they cannot start with a number and must start with a letter or underscore. For more details see the section on variables in this manual.

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

Use of $_SESSION (or $HTTP_SESSION_VARS with PHP 4.0.6 or less) is recommended for improved security and code readability. With $_SESSION, there is no need to use the session_register(), session_unregister(), session_is_registered() functions. Session variables are accessible like any other variables.

Example 1. Registering a variable with $_SESSION.

<?php
session_start
();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
if (!isset($_SESSION['count'])) {
    
$_SESSION['count'] = 0;
} else {
    
$_SESSION['count']++;
}
?>

Example 2. Unregistering a variable with $_SESSION and register_globals disabled.

<?php
session_start
();
// Use $HTTP_SESSION_VARS with PHP 4.0.6 or less
unset($_SESSION['count']);
?>

Caution

Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.

Warning

You can't use references in session variables as there is no feasible way to restore a reference to another variable.

If register_globals is enabled, then each global variable can be registered as session variable. Upon a restart of a session, these variables will be restored to corresponding global variables. Since PHP must know which global variables are registered as session variables, users need to register variables with session_register() function. You can avoid this by simply setting entries in $_SESSION.

Caution

Before PHP 4.3, if you are using $_SESSION and you have disabled register_globals, don't use session_register(), session_is_registered() or session_unregister(). Disabling register_globals is recommended for both security and performance reasons.

If register_globals is enabled, then the global variables and the $_SESSION entries will automatically reference the same values which were registered in the prior session instance. However, if the variable is registered by $_SESSION then the global variable is available since the next request.

There is a defect in PHP 4.2.3 and earlier. If you register a new session variable by using session_register(), the entry in the global scope and the $_SESSION entry will not reference the same value until the next session_start(). I.e. a modification to the newly registered global variable will not be reflected by the $_SESSION entry. This has been corrected in PHP 4.3.

Passing the Session ID

There are two methods to propagate a session id:

  • Cookies

  • URL parameter

The session module supports both methods. Cookies are optimal, but because they are not always available, we also provide an alternative way. The second method embeds the session id directly into URLs.

PHP is capable of transforming links transparently. Unless you are using PHP 4.2 or later, you need to enable it manually when building PHP. Under Unix, pass --enable-trans-sid to configure. If this build option and the run-time option session.use_trans_sid are enabled, relative URIs will be changed to contain the session id automatically.

Note: The arg_separator.output php.ini directive allows to customize the argument seperator. For full XHTML conformance, specify &amp; there.

Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs.

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
if (!session_is_registered('count')) {
    
session_register('count');
    
$count 1;
} else {
    
$count++;
}
?>

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

<p>
To continue, <a href="nextpage.php?<?php echo strip_tags(SID); ?>">click
here</a>.
</p>

The strip_tags() is used when printing the SID in order to prevent XSS related attacks.

Printing the SID, like shown above, is not necessary if --enable-trans-sid was used to compile PHP.

Note: Non-relative URLs are assumed to point to external sites and hence don't append the SID, as it would be a security risk to leak the SID to a different server.

Custom Session Handlers

To implement database storage, or any other storage method, you will need to use session_set_save_handler() to create a set of user-level storage functions.

Table of Contents
session_cache_expire -- Return current cache expire
session_cache_limiter -- Get and/or set the current cache limiter
session_commit -- Alias of session_write_close()
session_decode -- Decodes session data from a string
session_destroy -- Destroys all data registered to a session
session_encode --  Encodes the current session data as a string
session_get_cookie_params --  Get the session cookie parameters
session_id -- Get and/or set the current session id
session_is_registered --  Find out whether a global variable is registered in a session
session_module_name -- Get and/or set the current session module
session_name -- Get and/or set the current session name
session_regenerate_id --  Update the current session id with a newly generated one
session_register --  Register one or more global variables with the current session
session_save_path -- Get and/or set the current session save path
session_set_cookie_params --  Set the session cookie parameters
session_set_save_handler --  Sets user-level session storage functions
session_start -- Initialize session data
session_unregister --  Unregister a global variable from the current session
session_unset --  Free all session variables
session_write_close -- Write session data and end session