= 4_1_0, PHP_5, PHP_7, PHP_8 // ============================== USING FUNCTIONS (23) // OFFLINE | session_abort() - PHP_5 >= PHP_5_6_0, PHP_7, PHP_8 // session_cache_expire() - PHP_4 >= PHP_4_2_0, PHP_5, PHP_7, PHP_8 // session_cache_limiter() - PHP_4 >= PHP_4_0_3, PHP_5, PHP_7, PHP_8 // session_commit() - PHP_4 >= PHP_4_4_0, PHP_5, PHP_7, PHP_8 // OFFLINE | session_create_id() - PHP_7 >= PHP_7_1_0, PHP_8 // session_decode() - PHP_4, PHP_5, PHP_7, PHP_8 // session_destroy() - PHP_4, PHP_5, PHP_7, PHP_8 // session_encode() - PHP_4, PHP_5, PHP_7, PHP_8 // OFFLINE | session_gc() - PHP_7 >= PHP_7_1_0, PHP_8 // session_get_cookie_params() - PHP_4, PHP_5, PHP_7, PHP_8 // session_id() - PHP_4, PHP_5, PHP_7, PHP_8 // session_module_name() - PHP_4, PHP_5, PHP_7, PHP_8 // session_name() - PHP_4, PHP_5, PHP_7, PHP_8 // session_regenerate_id() - PHP_4 >= PHP_4_3_2, PHP_5, PHP_7, PHP_8 // OFFLINE | session_register_shutdown() - PHP_5 >= PHP_5_4_0, PHP_7, PHP_8 // OFFLINE | session_reset() - PHP_5 >= PHP_5_6_0, PHP_7, PHP_8 // session_save_path() - PHP_4, PHP_5, PHP_7, PHP_8 // session_set_cookie_params() - PHP_4, PHP_5, PHP_7, PHP_8 // session_set_save_handler() - PHP_4, PHP_5, PHP_7, PHP_8 // session_start() - PHP_4, PHP_5, PHP_7, PHP_8 // OFFLINE | session_status() - PHP_5 >= PHP_5_4_0, PHP_7, PHP_8 // session_unset() - PHP_4, PHP_5, PHP_7, PHP_8 // session_write_close() - PHP_4 >= PHP_4_0_4, PHP_5, PHP_7, PHP_8 // ============================== USING CLASSES (0) // ============================== USING DATA_TYPES (7) // array // bool // int // false // string // void // object // ============================== END // REQUIREMENTS // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS // ============================== ABOUT // PHP Manual / Function Reference / Session Extensions / Sessions - Session Handling // URL: https://www.php.net/manual/en/book.session.php // ============================== DESCRIPTION // SESSION_HANDLING // // SESSION_HANDLING - BEGIN // Session Handling // // INTRODUCTION // INSTALLING_CONFIGURING // PREDEFINED_CONSTANTS // EXAMPLES // SESSION_UPLOAD_PROGRESS // SESSIONS_AND_SECURITY // SESSION_FUNCTIONS // THE_SESSIONHANDLER_CLASS // THE_SESSIONHANDLERINTERFACE_CLASS // THE_SESSIONIDINTERFACE_INTERFACE // THE_SESSIONUPDATETIMESTAMPHANDLERINTERFACE_INTERFACE // // INTRODUCTION - BEGIN // Introduction // // Session support in PHP consists of a way to preserve certain data across subsequent accesses. // 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 store data between requests in the $_SESSION superglobal array. 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()) 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 turn on session.auto_start then the only way to put objects into your sessions is to load its class definition using auto_prepend_file in which you load the class definition else you will have to serialize() your object and unserialize() it afterwards. // $_SESSION (and all registered variables) are serialized internally by PHP using the serialization handler specified by the session.serialize_handler ini setting, 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: Because session data is serialized, resource variables cannot be stored in the session. // Serialize handlers (php and php_binary) inherit register_globals limitations. Therefore, numeric index or string index contains special characters (| and !) cannot be used. Using these will end up with errors at script shutdown. php_serialize does not have such limitations. // 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. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/intro.session.php // INTRODUCTION - END // // INSTALLING_CONFIGURING - BEGIN // Installing/Configuring // // REQUIREMENTS // INSTALLATION // RUNTIME_CONFIGURATION // RESOURCE_TYPES // // REQUIREMENTS - BEGIN // 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. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/session.requirements.php // REQUIREMENTS - END // // INSTALLATION - BEGIN // 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 extensions 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. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/session.installation.php // INSTALLATION - END // // RUNTIME_CONFIGURATION - BEGIN // Runtime Configuration // // The behaviour of these functions is affected by settings in php.ini. // // Session configuration options // Name | Default | Changeable | Changelog // 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_PERDIR | // session.gc_probability | "1" | PHP_INI_ALL | // session.gc_divisor | "100" | PHP_INI_ALL | // 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 | "0" | PHP_INI_ALL | Prior to PHP 7.2.0, the default was "". // session.cookie_httponly | "0" | PHP_INI_ALL | Prior to PHP 7.2.0, the default was "". // session.cookie_samesite | "" | PHP_INI_ALL | Available as of PHP 7.3.0. // session.use_strict_mode | "0" | PHP_INI_ALL | // session.use_cookies | "1" | PHP_INI_ALL | // session.use_only_cookies | "1" | PHP_INI_ALL | // session.referer_check | "" | PHP_INI_ALL | // session.cache_limiter | "nocache" | PHP_INI_ALL | // session.cache_expire | "180" | PHP_INI_ALL | // session.use_trans_sid | "0" | PHP_INI_ALL | // session.trans_sid_tags | "a=href,area=href,frame=src,form=" | PHP_INI_ALL | Available as of PHP 7.1.0. // session.trans_sid_hosts | $_SERVER['HTTP_HOST'] | PHP_INI_ALL | Available as of PHP 7.1.0. // session.sid_length | "32" | PHP_INI_ALL | Available as of PHP 7.1.0. // session.sid_bits_per_character | "4" | PHP_INI_ALL | Available as of PHP 7.1.0. // session.upload_progress.enabled | "1" | PHP_INI_PERDIR | // session.upload_progress.cleanup | "1" | PHP_INI_PERDIR | // session.upload_progress.prefix | "upload_progress_" | PHP_INI_PERDIR | // session.upload_progress.name | "PHP_SESSION_UPLOAD_PROGRESS" | PHP_INI_PERDIR | // session.upload_progress.freq | "1%" | PHP_INI_PERDIR | // session.upload_progress.min_freq | "1" | PHP_INI_PERDIR | // session.lazy_write | "1" | PHP_INI_ALL | // session.hash_function | "0" | PHP_INI_ALL | Removed as of PHP 7.1.0. // session.hash_bits_per_character | "4" | PHP_INI_ALL | Removed as of PHP 7.1.0. // session.entropy_file | "" | PHP_INI_ALL | Removed as of PHP 7.1.0. // session.entropy_length | "0" | PHP_INI_ALL | Removed as of PHP 7.1.0 // // For further details and definitions of the PHP_INI_* modes, see the Where a configuration setting may be set. // 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. Note that individual extensions may register their own save_handlers; registered handlers can be obtained on a per-installation basis by referring to phpinfo(). 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. 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, with a Windows version called mod_files.bat. 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. // The file storage module creates files using mode 600 by default. This default can be changed with the optional MODE argument: N;MODE;/path where MODE is the octal representation of the mode. Setting MODE does not affect the process umask. // Warning: If this is 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. // Caution: When using the optional directory level argument N, as described above, note that using a value higher than 1 or 2 is inappropriate for most sites due to the large number of directories required: for example, a value of 3 implies that (2 ** session.sid_bits_per_character) ** 3 directories exist on the filesystem, which can result in a lot of wasted space and inodes. // Only use N greater than 2 if you are absolutely certain that your site is large enough to require it. // 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 bool - 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. PHP serialize format (name php_serialize), PHP internal formats (name php and php_binary) and WDDX are supported (name wddx). WDDX is only available, if PHP is compiled with WDDX support. php_serialize uses plain serialize/unserialize function internally and does not have limitations that php and php_binary have. Older serialize handlers cannot store numeric index nor string index contains special characters (| and !) in $_SESSION. Use php_serialize to avoid numeric index or special character errors at script shutdown. Defaults to php. // session.gc_probability int - 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 int - 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 int - session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and potentially cleaned up. Garbage collection may occur during session start (depending on session.gc_probability and session.gc_divisor). Defaults to 1440 (24 minutes). // 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. // 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. This feature is supported on Windows. Setting session.entropy_length to a non zero value will make PHP use the Windows Random API as entropy source. // Note: Removed in PHP 7.1.0. session.entropy_file defaults to /dev/urandom or /dev/arandom if it is available. // session.entropy_length int - session.entropy_length specifies the number of bytes which will be read from the file specified above. Defaults to 32. Removed in PHP 7.1.0. // session.use_strict_mode bool - session.use_strict_mode specifies whether the module will use strict session id mode. If this mode is enabled, the module does not accept uninitialized session IDs. If an uninitialized session ID is sent from the browser, a new session ID is sent to the browser. Applications are protected from session fixation via session adoption with strict mode. Defaults to 0 (disabled). // Note: Enabling session.use_strict_mode is mandatory for general session security. All sites are advised to enable this. See session_create_id() example code for more details. // Warning: If a custom session handler registered via session_set_save_handler() does not implement SessionUpdateTimestampHandlerInterface::validateId(), nor supplies the validate_sid callback, respectively, strict session ID mode is effectively disabled, regardless of the value of this directive. Particularly note that SessionHandler does not implement SessionHandler::validateId(). // session.use_cookies bool - 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 bool - 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. Defaults to 1 (enabled). // session.cookie_lifetime int - 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(). // Note: The expiration timestamp is set relative to the server time, which is not necessarily the same as the time in the client's browser. // session.cookie_path string - session.cookie_path specifies path to set in the 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 the 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 bool - session.cookie_secure specifies whether cookies should only be sent over secure connections. Defaults to off. See also session_get_cookie_params() and session_set_cookie_params(). // session.cookie_httponly bool - 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.cookie_samesite string - Allows servers to assert that a cookie ought not to be sent along with cross-site requests. This assertion allows user agents to mitigate the risk of cross-origin information leakage, and provides some protection against cross-site request forgery attacks. Note that this is not supported by all browsers. An empty value means that no SameSite cookie attribute will be set. Lax and Strict mean that the cookie will not be sent cross-domain for POST requests; Lax will sent the cookie for cross-domain GET requests, while Strict will not. // session.cache_limiter string - session.cache_limiter specifies the cache control method used for session pages. It may be one of the following values: nocache, private, private_no_expire, or public. Defaults to nocache. See also the session_cache_limiter() documentation for information about what these values mean. // session.cache_expire int - 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 bool - session.use_trans_sid whether transparent sid support is enabled or not. Defaults to 0 (disabled). // Note: 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. Since PHP 7.1.0, full URL path, e.g. https://php.net/, is handled by trans sid feature. Previous PHP handled relative URL path only. Rewrite target hosts are defined by session.trans_sid_hosts. // session.trans_sid_tags string - session.trans_sid_tags specifies which HTML tags are rewritten to include session id when transparent sid support is enabled. Defaults to a=href,area=href,frame=src,input=src,form= form is special tag. is added as form variable. // Note: Before PHP 7.1.0, url_rewriter.tags was used for this purpose. Since PHP 7.1.0, fieldset is no longer considered as special tag. // session.trans_sid_hosts string - session.trans_sid_hosts specifies which hosts are rewritten to include session id when transparent sid support is enabled. Defaults to $_SERVER['HTTP_HOST'] Multiple hosts can be specified by ",", no space is allowed between hosts. e.g. php.net,wiki.php.net,bugs.php.net // session.sid_length int - session.sid_length allows you to specify the length of session ID string. Session ID length can be between 22 to 256. The default is 32. If you need compatibility you may specify 32, 40, etc. Longer session ID is harder to guess. At least 32 chars are recommended. // Tip: Compatibility Note: Use 32 instead of session.hash_function=0 (MD5) and session.hash_bits_per_character=4, session.hash_function=1 (SHA1) and session.hash_bits_per_character=6. Use 26 instead of session.hash_function=0 (MD5) and session.hash_bits_per_character=5. Use 22 instead of session.hash_function=0 (MD5) and session.hash_bits_per_character=6. You must configure INI values to have at least 128 bits in session ID. Do not forget to set an appropriate value for session.sid_bits_per_character, otherwise you will have weaker session ID. // Note: This setting is introduced in PHP 7.1.0. // session.sid_bits_per_character int - session.sid_bits_per_character allows you to specify the number of bits in encoded session ID character. The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ","). The default is 4. The more bits results in stronger session ID. 5 is recommended value for most environments. // Note: This setting is introduced in PHP 7.1.0. // session.hash_function mixed - 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). // It is also possible to specify any of the algorithms provided by the hash extension (if it is available), like sha512 or whirlpool. A complete list of supported algorithms can be obtained with the hash_algos() function. // Note: Removed in PHP 7.1.0. // session.hash_bits_per_character int - 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: Removed in PHP 7.1.0. // session.upload_progress.enabled bool - Enables upload progress tracking, populating the $_SESSION variable. Defaults to 1, enabled. // session.upload_progress.cleanup bool - Cleanup the progress information as soon as all POST data has been read (i.e. upload completed). Defaults to 1, enabled. // Note: It is highly recommended to keep this feature enabled. // session.upload_progress.prefix string - A prefix used for the upload progress key in the $_SESSION. This key will be concatenated with the value of $_POST[ini_get("session.upload_progress.name")] to provide a unique index. Defaults to "upload_progress_". // session.upload_progress.name string - The name of the key to be used in $_SESSION storing the progress information. See also session.upload_progress.prefix. If $_POST[ini_get("session.upload_progress.name")] is not passed or available, upload progressing will not be recorded. Defaults to "PHP_SESSION_UPLOAD_PROGRESS". // session.upload_progress.freq mixed - Defines how often the upload progress information should be updated. This can be defined in bytes (i.e. "update progress information after every 100 bytes"), or in percentages (i.e. "update progress information after receiving every 1% of the whole filesize"). Defaults to "1%". // session.upload_progress.min_freq int - The minimum delay between updates, in seconds. Defaults to "1" (one second). // session.lazy_write bool - session.lazy_write, when set to 1, means that session data is only rewritten if it changes. Defaults to 1, enabled. // // Upload progress will not be registered unless session.upload_progress.enabled is enabled, and the $_POST[ini_get("session.upload_progress.name")] variable is set. See Session Upload Progress for more details on this functionality. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/session.configuration.php // RUNTIME_CONFIGURATION - END // // RESOURCE_TYPES - BEGIN // Resource Types // // This extension has no resource types defined. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/session.resources.php // RESOURCE_TYPES - END // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/session.setup.php // INSTALLING_CONFIGURING - END // // PREDEFINED_CONSTANTS - BEGIN // 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. This is the same id as the one returned by session_id(). // PHP_SESSION_DISABLED (int) - Return value of session_status() if sessions are disabled. // PHP_SESSION_NONE (int) - Return value of session_status() if sessions are enabled, but no session exists. // PHP_SESSION_ACTIVE (int) - Return value of session_status() if sessions are enabled, and a session exists. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/session.constants.php // PREDEFINED_CONSTANTS - END // // EXAMPLES - BEGIN // Examples // // BASIC_USAGE // PASSING_THE_SESSION_ID // CUSTOM_SESSION_HANDLERS // // BASIC_USAGE - BEGIN // Basic usage // // Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data. The absence of an ID or session cookie lets PHP know to create a new session, and generate a new session ID. // Sessions follow a simple workflow. When a session is started, PHP will either retrieve an existing session using the ID passed (usually from a session cookie) or if no session is passed it will create a new session. PHP will populate the $_SESSION superglobal with any session data after the session has started. When PHP shuts down, it will automatically take the contents of the $_SESSION superglobal, serialize it, and send it for storage using the session save handler. // By default, PHP uses the internal files save handler which is set by session.save_handler. This saves session data on the server at the location specified by the session.save_path configuration directive. // Sessions can be started manually using the session_start() function. If the session.auto_start directive is set to 1, a session will automatically start on request startup. // Sessions normally shutdown automatically when PHP is finished executing a script, but can be manually shutdown using the session_write_close() function. // [example] // Example #1 Registering a variable with $_SESSION. // [php] // session_start(); // if (!isset($_SESSION['count'])) { // $_SESSION['count'] = 0; // } else { // $_SESSION['count']++; // } // [/php] // [/example] // [example] // Example #2 Unregistering a variable with $_SESSION. // [php] // session_start(); // unset($_SESSION['count']); // [/php] // [/example] // 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. // Note: // File based sessions (the default in PHP) lock the session file once a session is opened via session_start() or implicitly via session.auto_start. Once locked, no other script can access the same session file until it has been closed by the first script terminating or calling session_write_close(). // This is most likely to be an issue on Web sites that use AJAX heavily and have multiple concurrent requests. The easiest way to deal with it is to call session_write_close() as soon as any required changes to the session have been made, preferably early in the script. Alternatively, a different session backend that does support concurrency could be used. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/session.examples.basic.php // BASIC_USAGE - END // // PASSING_THE_SESSION_ID - BEGIN // 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. If the run-time option session.use_trans_sid is 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 separator. For full XHTML conformance, specify & 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] // Example #1 Counting the number of hits of a single user // [code] // [php] // // session_start(); // // if (empty($_SESSION['count'])) { // $_SESSION['count'] = 1; // } else { // $_SESSION['count']++; // } // [/php] // //
// Hello visitor, you have seen this page [php] echo $_SESSION['count']; [/php] times. //
// //// To continue, click // here. //
// [/code] // [/example] // The htmlspecialchars() may be 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. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/session.idpassing.php // PASSING_THE_SESSION_ID - END // // CUSTOM_SESSION_HANDLERS - BEGIN // 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. A session handlers may be created using the SessionHandlerInterface or extending PHP's internal handlers by inheriting from SessionHandler. // The callbacks specified in session_set_save_handler() are methods called by PHP during the life-cycle of a session: open, read, write and close and for the housekeeping tasks: destroy for deleting a session and gc for periodic garbage collection. // Therefore, PHP always requires session save handlers. The default is usually the internal 'files' save handler. A custom save handler can be set using session_set_save_handler(). Alternative internal save handlers are also provided by PHP extensions, such as sqlite, memcache and memcached and can be set with session.save_handler. // When the session starts, PHP will internally call the open handler followed by the read callback which should return an encoded string exactly as it was originally passed for storage. Once the read callback returns the encoded string, PHP will decode it and then populate the resulting array into the $_SESSION superglobal. // When PHP shuts down (or when session_write_close() is called), PHP will internally encode the $_SESSION superglobal and pass this along with the session ID to the write callback. After the write callback has finished, PHP will internally invoke the close callback handler. // When a session is specifically destroyed, PHP will call the destroy handler with the session ID. // PHP will call the gc callback from time to time to expire any session records according to the set max lifetime of a session. This routine should delete all records from persistent storage which were last accessed longer than the $lifetime. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/session.customhandler.php // CUSTOM_SESSION_HANDLERS - END // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/session.examples.php // EXAMPLES - END // // SESSION_UPLOAD_PROGRESS - BEGIN // Session Upload Progress // // When the session.upload_progress.enabled INI option is enabled, PHP will be able to track the upload progress of individual files being uploaded. This information isn't particularly useful for the actual upload request itself, but during the file upload an application can send a POST request to a separate endpoint (via XHR for example) to check the status. // The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. The key is typically retrieved by reading these INI settings, i.e. // [php] // $key = ini_get("session.upload_progress.prefix") . $_POST[ini_get("session.upload_progress.name")]; // var_dump($_SESSION[$key]); // [/php] // It is also possible to cancel the currently in-progress file upload, by setting the $_SESSION[$key]["cancel_upload"] key to true. When uploading multiple files in the same request, this will only cancel the currently in-progress file upload, and pending file uploads, but will not remove successfully completed uploads. When an upload is cancelled like this, the error key in $_FILES array will be set to UPLOAD_ERR_EXTENSION. // The session.upload_progress.freq and session.upload_progress.min_freq INI options control how frequent the upload progress information should be recalculated. With a reasonable amount for these two settings, the overhead of this feature is almost non-existent. // [example] // Example #1 Example information // Example of the structure of the progress upload array. // [code] // // [/code] // The data stored in the session will look like this: // [php] // $_SESSION["upload_progress_123"] = array( // "start_time" => 1234567890, // The request time // "content_length" => 57343257, // POST content length // "bytes_processed" => 453489, // Amount of bytes received and processed // "done" => false, // true when the POST handler has finished, successfully or not // "files" => array( // 0 => array( // "field_name" => "file1", // Name of the field // // The following 3 elements equals those in $_FILES // "name" => "foo.avi", // "tmp_name" => "/tmp/phpxxxxxx", // "error" => 0, // "done" => true, // True when the POST handler has finished handling this file // "start_time" => 1234567890, // When this file has started to be processed // "bytes_processed" => 57343250, // Number of bytes received and processed for this file // ), // // An other file, not finished uploading, in the same request // 1 => array( // "field_name" => "file2", // "name" => "bar.avi", // "tmp_name" => NULL, // "error" => 0, // "done" => false, // "start_time" => 1234567899, // "bytes_processed" => 54554, // ), // ) // ); // [/php] // [/example] // Warning: The web server's request buffering has to be disabled for this to work properly, else PHP may see the file upload only once fully uploaded. Servers such as Nginx are known to buffer larger requests. // Caution: The upload progress information is written to the session before any scripts are executed. Therefore changing the session name via ini_set() or session_name() will give a session without the upload progress information. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/session.upload-progress.php // SESSION_UPLOAD_PROGRESS - END // // SESSIONS_AND_SECURITY - BEGIN // Sessions and Security // // SESSION_MANAGEMENT_BASICS // SECURING_SESSION_INI_SETTINGS // // External links: > Session fixation // HTTP session management represents the core of web security. All possible mitigation measures should be adopted to ensure sessions are secured. Developers should also enable/use applicable security measures. // // SESSION_MANAGEMENT_BASICS - BEGIN // Session Management Basics // // Session Security // The session module can not guarantee that the information stored in a session is only viewed by the user who created the session. Additional measures are needed to protect the confidentiality of the session, depending on the value associated with it. // The importance of the data carried in the session needs to be assessed and further protection may be deployed; this typically comes at a price, such as reduced convenience for the user. For example, to protect users from a simple social engineering tactic, session.use_only_cookies needs to be enabled. In that case, cookies must be enabled unconditionally on the client side, or sessions will not work. // There are several ways to leak an existing session ID to third parties. E.g. JavaScript injections, session IDs in URLs, packet sniffing, physical access to the device, etc. A leaked session ID enables the third party to access all resources associated with a specific ID. First, URLs carrying session IDs. If there are links to an external site or resource, the URL including the session ID might be stored in the external site's referrer logs. Second, a more active attacker might listen to network traffic. If it is unencrypted, session IDs will flow in plain text over the network. The solution is to implement SSL/TLS on the server and make it mandatory for users. HSTS should be used for improved security. // Note: Even HTTPS can not protect confidential data at all times. For example the CRIME and Beast vulnerabilities may enable an attacker to read the data. Also, note that many networks employ HTTPS MITM proxies for audit purposes. Attackers may also set up such a proxy. // // Non-adaptive Session Management // PHP's session manager is adaptive by default currently. An adaptive session manager bears additional risks. // When session.use_strict_mode is enabled, and the session save handler supports it, an uninitialized session ID is rejected and a new one is created. This prevents an attack that forces users to use a known session ID. An attacker may paste links or send emails that contains the session ID. E.g. http://example.com/page.php?PHPSESSID=123456789 if session.use_trans_sid is enabled, the victim will start a session using the session ID provided by the attacker. session.use_strict_mode mitigate this risk. // Warning: User defined save handlers can also support strict session mode by implementing session ID validation. All user defined save handlers should implement session ID validation. // The session ID cookie may be set with the domain, path, httponly, secure and, as of PHP 7.3, SameSite attributes. There is precedence defined by browsers. By using the precedence, an attacker can set session ID that could be used permanently. Use of session.use_only_cookies will not solve this issue. session.use_strict_mode mitigates this risk. With session.use_strict_mode=On, the uninitialized session ID will be refused. // Note: Even though session.use_strict_mode mitigates the risk of adaptive session management, an attacker can force users to use an initialized session ID which has been created by an attacker. E.g. JavaScript injection. This attack can be mitigated by this manual's recommendations. By following this manual, developers should enable, session.use_strict_mode, use timestamp based session management, and regenerate session IDs using session_regenerate_id() with recommended procedures. If developers follow all of the above, an attacker generated session ID will eventually be deleted. When access to an obsolete session occurs, developers should save all active session data of the user. As this information will be relevant for an ensuing investigation. The user should be forcefully logged out of all sessions, i.e. require them to reauthenticate. This prevents attackers from abusing stolen sessions. // Warning: Access to an obsolete session does not necessarily suggest an attack. An unstable network and/or immediate deletion of the active session will result in legitimate users using obsolete sessions. // As of PHP 7.1.0, session_create_id() has been added. This function may be operated to access all active sessions of a user efficiently by prefixing the session IDs with the user ID. Enabling session.use_strict_mode is vital with this setup. Otherwise, malicious users can set malicious session ID for other users. // Note: Users prior to PHP 7.1.0 should use CSPRNG, e.g. /dev/urandom, or random_bytes() and hash functions to generate a new session ID. session_create_id() has collision detection and generates a session ID according to the session's INI settings. Use of session_create_id() is preferred. // // Session ID Regeneration // session.use_strict_mode is a good mitigation, however not sufficient. Developers must equally use session_regenerate_id() for session security. // Session ID regeneration reduces the risk of stolen session IDs, thus session_regenerate_id() must be called periodically. E.g. Regenerate the session ID every 15 minutes for security sensitive content. Even in the case that a session ID is stolen, both the legitimate user's and the attacker's session will expire. In other words access by the user or the attacker will generate an obsolete session access error. // Session IDs must be regenerated when user privileges are elevated, such as after authenticating. session_regenerate_id() must be called prior to setting the authentication information to $_SESSION. (session_regenerate_id() saves the current session data automatically in order to save timestamp/etc. to the current session.) Ensure only the new session contains the authenticated flag. // Developers must not rely on session ID expiration by session.gc_maxlifetime. Attackers may access a victim's session ID periodically to prevent its expiration and keep exploiting it, including an authenticated session. // Instead, developers must implement timestamp based session data management. // Warning: Although the session manager can manage timestamps transparently, this feature is not implemented. Old session data must be kept until GC. Simultaneously, developers must assure themselves obsolete session data is removed. However, developers must not remove active session data immediately. I.e. session_regenerate_id(true); and session_destroy() must never be called together for an active session. This may sound contradictory, but this is a mandatory requirement. // session_regenerate_id() does not delete outdated sessions by default. Obsolete authenticated sessions may be present for use. Developers must prevent outdated sessions to be consumed by anyone. They must prohibit access to obsolete session data by themselves using timestamps. // Warning: The sudden removal of an active session produces undesirable side effects. Sessions can vanish when there are concurrent connections to the web application and/or the network is unstable. // Potential malicious access is undetectable with the sudden removal of active sessions. // Instead of deleting outdated sessions immediately, developers must set a short-term expiration time (timestamp) in $_SESSION, and prohibit access to the session data by themselves. // Developers must not prohibit access to old session data immediately after session_regenerate_id(). It must be prohibited at a later stage. E.g. a few seconds later for stable networks, like a wired network, and a few minutes later for unstable networks such as cell phones or Wi-Fi. // If a user accesses an obsolete session (expired session), access to it should be denied. It is also recommended to remove the authenticated status from all of the user's sessions to as it is likely to represent an attack. // Proper use of session.use_only_cookies and session_regenerate_id() can cause personal DoS with undeletable cookies set by attackers. In this case, developers may invite users to remove cookies and advise them they may be affected by a security issue. Attackers may set malicious cookies via a vulnerable web application, an exposed/vicious browser plugin, a physically compromised device, etc. // Warning: Do not misunderstand the DoS risk. session.use_strict_mode=On is mandatory for general session ID security! All sites are advised to enable session.use_strict_mode. // DoS can only happen when the account is under attack. A JavaScript injection vulnerability in an application represents the most common cause. // // Session Data Deletion // Obsolete session data must be inaccessible and deleted. The current session module does not handle this well. // Obsolete session data should be removed as soon as possible. However, active sessions must not be removed instantly. To satisfy those requirements, developers must implement timestamp based session data management by themselves. // Set and manage expiration timestamp in $_SESSION. Prohibit access to outdated session data. When access to obsolete session data is detected, it is advised to remove all authenticated status from the user's sessions and force them to re-authenticate. Access to obsolete session data can represent an attack. To achieve this, developers must keep track of all active sessions of every user. // Note: Access to an obsolete session can also happen because of an unstable network and/or concurrent access to the website. E.g. the server tried to set a new session ID via a cookie, but the Set-Cookie packet may not have reached the client due to loss of connection. One connection may issue a new session ID by session_regenerate_id(), but another concurrent connection may not have received the new session ID yet. Therefore, developers must prohibit access to obsolete session at a later stage. I.e. timestamp based session management is mandatory. // In summary, session data must not be destroyed with session_regenerate_id() nor session_destroy(), but timestamps must be used to control access to session data. Let session_gc() remove obsolete data from the session data storage. // // Session and Locking // Session data is locked to avoid race conditions by default. Locking is mandatory to keep session data consistent across requests. // However, session-locking can be abused by attackers to perform DoS attacks. To mitigate the risk of a DoS attack by session-locking, minimize locks. Use read only sessions when session data does not need to be updated. Use the 'read_and_close' option with session_start(). session_start(['read_and_close'=>1]); Close the session as soon as possible after updating $_SESSION by using session_commit(). // The current session module does not detect any modification of $_SESSION when the session is inactive. It is the developer's responsibility not to modify $_SESSION when the session is inactive. // // Active Sessions // Developers should keep track of all active sessions for every user. And notify them of how many active sessions, from which IP (and area), how long it has been active, etc. PHP does not keep track of these. Developers are supposed to do so. // Various ways to implement this exist. One possible implementation is setting up a database that keeps track of the required data and stores any relevant information. Since session data is GCed, developers must take care of the GCed data to maintain the active session database consistency. // One of the simplest implementations is "User ID prefixed session ID" and store the required information in $_SESSION. Many databases posses good performance for selecting string prefix. Developers MAY use session_regenerate_id() and session_create_id() for this. // Warning: Never employ confidential data as a prefix. If the user ID is confidential, consider using hash_hmac(). // Warning: Enabling session.use_strict_mode is mandatory for this setup. Ensure it is enabled. Otherwise, the active session database can be compromised. // Timestamp based session management is mandatory to detect access to obsolete sessions. When access to an obsolete session is detected, authentication flags should be removed from all active sessions of the user. This prevents attackers to keep exploiting stolen sessions. // // Session and Auto-login // Developers must not use long life session IDs for auto-login because it increases the risk of stolen sessions. An auto-login feature should be implemented by the developer. // Use a secure one time hash key as an auto-login key using setcookie(). Use a secure hash stronger than SHA-2. E.g. SHA-256 or greater with random data from random_bytes() or /dev/urandom. // If the user is unauthenticated, check whether the one-time auto-login key is valid or not. In the case it is valid, authenticate the user and set a new secure one-time hash key. An auto-login key must only be used once, i.e. never reuse an auto-login key, always generate a new one. // An auto-login key is a long life authentication key, it should be protected as much as possible. Use path/httponly/secure/SameSite cookie attributes to secure it. I.e. never transmit the auto-login key unless required. // Developer must implement the features that disables auto-login and removes unneeded auto-login key cookie. // // CSRF (Cross-Site Request Forgeries) attacks // Sessions and authentication do not protect against CSRF attacks. Developers must implement CSRF protection by themselves. // output_add_rewrite_var() can be used for CSRF protection. Refer to the manual page for more details. // Note: PHP prior to 7.2.0 uses the same output buffer and INI setting as trans sid. Therefore, use of output_add_rewrite_var() with PHP prior to version 7.2.0 is not advised. // Most web application frameworks support CSRF protection. Refer to the web application framework manual for more details. // As of PHP 7.3 the SameSite attribute for the session cookie can be set. This is an additional measure which can mitigate CSRF vulnerabilities. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/features.session.security.management.php // SESSION_MANAGEMENT_BASICS - END // // SECURING_SESSION_INI_SETTINGS - BEGIN // Securing Session INI Settings // // By securing session related INI settings, developers can improve session security. Some important INI settings do not have any recommended settings. Developers are responsible for hardening session settings. // * session.cookie_lifetime=0 // 0 possesses a particular meaning. It informs browsers not to store the cookie to permanent storage. Therefore, when the browser is terminated, the session ID cookie is deleted immediately. If developers set this other than 0, it may allow other users to use the session ID. Most applications should use "0" for this. // If an auto-login feature is required, developers must implement their own secure auto-login feature. Do not use long life session IDs for this. More information can be found above in the relevant section. // * session.use_cookies=On // session.use_only_cookies=On // Although HTTP cookies suffer some problems, cookies remain the preferred way to manage session IDs. Only use cookies for session ID management when it is possible. Most applications should use a cookie for the session ID. // If session.use_only_cookies=Off, the session module will use the session ID values set by GET or POST provided the session ID cookie is uninitialized. // * session.use_strict_mode=On // Although, enabling session.use_strict_mode is mandatory for secure sessions. It is disabled by default. // This prevents the session module to use an uninitialized session ID. Put differently, the session module only accepts valid session IDs generated by the session module. It rejects any session ID supplied by users. // Due to the cookie specification, attackers are capable to place non-removable session ID cookies by locally setting a cookie database or JavaScript injections. session.use_strict_mode can prevent an attacker-initialized session ID of being used. // Note: Attackers may initialize a session ID with their device and may set the session ID of the victim. They must keep the session ID active to abuse. Attackers require additional steps to perform an attack in this scenario. Therefore, session.use_strict_mode works as a mitigation. // * session.cookie_httponly=On // Refuses access to the session cookie from JavaScript. This setting prevents cookies snatched by a JavaScript injection. // It is possible to use a session ID as a CSRF token, but this is not recommended. For example, HTML sources may be saved and sent to other users. Developers should not write session IDs in web pages for better security. Almost all applications must use the httponly attribute for the session ID cookie. // Note: The CSRF token should be renewed periodically just like the session ID. // * session.cookie_secure=On // Allow access to the session ID cookie only when the protocol is HTTPS. If a website is only accessible via HTTPS, it should enable this setting. // HSTS should be considered for websites accessible only via HTTPS. // * session.cookie_samesite="Lax" or session.cookie_samesite="Strict" // As of PHP 7.3 the "SameSite" attribute can be set for the session ID cookie. This attribute is a way to mitigate CSRF (Cross Site Request Forgery) attacks. // The difference between Lax and Strict is the accessibility of the cookie in requests originating from another registrable domain employing the HTTP GET method. Cookies using Lax will be accessible in a GET request originated from another registrable domain, whereas cookies using Strict will not. // * session.gc_maxlifetime=[choose smallest possible] // session.gc_maxlifetime is a setting for deleting obsolete session ID. Reliance on this setting is not recommended. Developers should manage the lifetime of sessions with a timestamp by themselves. // Session GC (garbage collection) is best performed by using session_gc(). The session_gc() function should be executed by a task managers. E.g. cron on UNIX like systems. // GC is performed by probability by default. This setting does not guarantee that an outdated session is deleted. Although developers cannot rely on this setting, specifying it to the smallest possible value is recommended. Adjusting session.gc_probability and session.gc_divisor so that obsolete sessions are deleted at an appropriate frequency. If an auto-login feature is required, developers must implement their own secure auto-login feature, see above for more information. Never use long life session ID for this feature. // Note: Some session save handler modules do not use this setting for probability based expiration. E.g. memcached, memcache. Refer to the session save handler documentation for details. // * session.use_trans_sid=Off // Use of a transparent session ID management is not prohibited. Developers may employ it when it is required. However, disabling transparent session ID management improves the general session ID security by eliminating the possibility of a session ID injection and/or leak. // Note: Session ID may leak from bookmarked URLs, e-mailed URLs, saved HTML source, etc. // * session.trans_sid_tags=[limited tags] // (PHP 7.1.0 >=) Developers should not rewrite unneeded HTML tags. Default value should be sufficient for most usages. Older PHP versions use url_rewriter.tags instead. // * session.trans_sid_hosts=[limited hosts] // (PHP 7.1.0 >=) This INI defines whitelist hosts that allows trans sid rewrite. Never add untrusted hosts. Session module only allows $_SERVER['HTTP_HOST'] when this setting is empty. // * session.referer_check=[originating URL] // When session.use_trans_sid is enabled. It reduces the risk of session ID injection. If a website is http://example.com/, set http://example.com/ to it. Note that with HTTPS browsers will not send the referrer header. Browsers may not send the referrer header by configuration. Therefore, this setting is not a reliable security measure. Use of this setting is recommended. // * session.cache_limiter=nocache // Ensure HTTP content are uncached for authenticated sessions. Allow caching only when the content is not private. Otherwise, content may be exposed. "private" may be employed if HTTP content does not include security sensitive data. Note that "private" may transmit private data cached by shared clients. "public" must only be used when HTTP content does not contain any private data at all. // * session.sid_length="48" // (PHP 7.1.0 >=) Longer session IDs results in stronger session IDs. Developers should consider a session ID length of 32 characters or more. At least 26 characters are required when session.sid_bits_per_character="5". // * session.sid_bits_per_character="6" // (PHP 7.1.0 >=) The more bits there are in a session ID character, the stronger the session ID generated by the session module is for an identical session ID length. // * session.hash_function="sha256" // (PHP 7.1.0 <) A stronger hash function will generate a stronger session ID. Although hash collision is unlikely even with the MD5 hashing algorithm, developers should use SHA-2 or a stronger hashing algorithm like sha384 and sha512. Developers must ensure they feed a long enough entropy for the hashing function used. // * session.save_path=[non world-readable directory] // If this is 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. // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/session.security.ini.php // SECURING_SESSION_INI_SETTINGS - END // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/session.security.php // SESSIONS_AND_SECURITY - END // // SESSION_FUNCTIONS - BEGIN // Session Functions // // Table of Contents: // * session_abort - Discard session array changes and finish session // * session_cache_expire - Get and/or set current cache expire // * session_cache_limiter - Get and/or set the current cache limiter // * session_commit - Alias of session_write_close // * session_create_id - Create new session id // * session_decode - Decodes session data from a session encoded string // * session_destroy - Destroys all data registered to a session // * session_encode - Encodes the current session data as a session encoded string // * session_gc - Perform session data garbage collection // * session_get_cookie_params - Get the session cookie parameters // * session_id - Get and/or set the current session id // * 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_shutdown - Session shutdown function // * session_reset - Re-initialize session array with original values // * 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 - Start new or resume existing session // * session_status - Returns the current session status // * session_unset - Free all session variables // * session_write_close - Write session data and end session // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/ref.session.php // SESSION_FUNCTIONS - END // // THE_SESSIONHANDLER_CLASS - BEGIN // The SessionHandler class // // PHP_5 >= PHP_5_4_0, PHP_7, PHP_8 // // Introduction // SessionHandler is a special class that can be used to expose the current internal PHP session save handler by inheritance. There are seven methods which wrap the seven internal session save handler callbacks (open, close, read, write, destroy, gc and create_sid). By default, this class will wrap whatever internal save handler is set as defined by the session.save_handler configuration directive which is usually files by default. Other internal session save handlers are provided by PHP extensions such as SQLite (as sqlite), Memcache (as memcache), and Memcached (as memcached). // When a plain instance of SessionHandler is set as the save handler using session_set_save_handler() it will wrap the current save handlers. A class extending from SessionHandler allows you to override the methods or intercept or filter them by calls the parent class methods which ultimately wrap the internal PHP session handlers. // This allows you, for example, to intercept the read and write methods to encrypt/decrypt the session data and then pass the result to and from the parent class. Alternatively one might chose to entirely override a method like the garbage collection callback gc. // Because the SessionHandler wraps the current internal save handler methods, the above example of encryption can be applied to any internal save handler without having to know the internals of the handlers. // To use this class, first set the save handler you wish to expose using session.save_handler and then pass an instance of SessionHandler or one extending it to session_set_save_handler(). // Please note that the callback methods of this class are designed to be called internally by PHP and are not meant to be called from user-space code. The return values are equally processed internally by PHP. For more information on the session workflow, please refer to session_set_save_handler(). // // Class synopsis // [code] // class SessionHandler implements SessionHandlerInterface, SessionIdInterface { // // /* Methods */ // public close(): bool // public create_sid(): string // public destroy(string $id): bool // public gc(int $max_lifetime): int|false // public open(string $path, string $name): bool // public read(string $id): string|false // public write(string $id, string $data): bool // } // [/code] // // Warning: This class is designed to expose the current internal PHP session save handler, if you want to write your own custom save handlers, please implement the SessionHandlerInterface interface instead of extending from SessionHandler. // [example] // Example #1 Using SessionHandler to add encryption to internal PHP save handlers. // [php] // // /** // * decrypt AES 256 // * // * @param data $edata // * @param string $password // * @return decrypted data // */ // function decrypt($edata, $password) { // $data = base64_decode($edata); // $salt = substr($data, 0, 16); // $ct = substr($data, 16); // // $rounds = 3; // depends on key length // $data00 = $password.$salt; // $hash = array(); // $hash[0] = hash('sha256', $data00, true); // $result = $hash[0]; // for ($i = 1; $i < $rounds; $i++) { // $hash[$i] = hash('sha256', $hash[$i - 1].$data00, true); // $result .= $hash[$i]; // } // $key = substr($result, 0, 32); // $iv = substr($result, 32,16); // // return openssl_decrypt($ct, 'AES-256-CBC', $key, true, $iv); // } // // /** // * crypt AES 256 // * // * @param data $data // * @param string $password // * @return base64 encrypted data // */ // function encrypt($data, $password) { // // Generate a cryptographically secure random salt using random_bytes() // $salt = random_bytes(16); // // $salted = ''; // $dx = ''; // // Salt the key(32) and iv(16) = 48 // while (strlen($salted) < 48) { // $dx = hash('sha256', $dx.$password.$salt, true); // $salted .= $dx; // } // // $key = substr($salted, 0, 32); // $iv = substr($salted, 32,16); // // $encrypted_data = openssl_encrypt($data, 'AES-256-CBC', $key, true, $iv); // return base64_encode($salt . $encrypted_data); // } // // class EncryptedSessionHandler extends SessionHandler // { // private $key; // // public function __construct($key) // { // $this->key = $key; // } // // public function read($id) // { // $data = parent::read($id); // // if (!$data) { // return ""; // } else { // return decrypt($data, $this->key); // } // } // // public function write($id, $data) // { // $data = encrypt($data, $this->key); // // return parent::write($id, $data); // } // } // // // we'll intercept the native 'files' handler, but will equally work // // with other internal native handlers like 'sqlite', 'memcache' or 'memcached' // // which are provided by PHP extensions. // ini_set('session.save_handler', 'files'); // // $key = 'secret_string'; // $handler = new EncryptedSessionHandler($key); // session_set_save_handler($handler, true); // session_start(); // // // proceed to set and retrieve values by key from $_SESSION // [/php] // [/example] // // Note: Since this class' methods are designed to be called internally by PHP as part of the normal session workflow, child class calls to parent methods (i.e. the actual internal native handlers) will return false unless the session has actually been started (either automatically, or by explicit session_start()). This is important to consider when writing unit tests where the class methods might be invoked manually. // // Table of Contents // * SessionHandler::close - Close the session // * SessionHandler::create_sid - Return a new session ID // * SessionHandler::destroy - Destroy a session // * SessionHandler::gc - Cleanup old sessions // * SessionHandler::open - Initialize session // * SessionHandler::read - Read session data // * SessionHandler::write - Write session data // // LITERATURE_SOURCES // * PHP_NET (2023-11-11) // URL: https://www.php.net/manual/en/class.sessionhandler.php // THE_SESSIONHANDLER_CLASS - END // // THE_SESSIONHANDLERINTERFACE_CLASS - BEGIN // The SessionHandlerInterface class // // PHP_5 >= PHP_5_4_0, PHP_7, PHP_8 // // Introduction // SessionHandlerInterface is an interface which defines the minimal prototype for creating a custom session handler. In order to pass a custom session handler to session_set_save_handler() using its OOP invocation, the class can implement this interface. // Please note the callback methods of this class are designed to be called internally by PHP and are not meant to be called from user-space code. // // Interface synopsis // [code] // interface SessionHandlerInterface { // // /* Methods */ // public close(): bool // public destroy(string $id): bool // public gc(int $max_lifetime): int|false // public open(string $path, string $name): bool // public read(string $id): string|false // public write(string $id, string $data): bool // } // [/code] // // [example] // Example #1 Example using SessionHandlerInterface // The following example provides file based session storage similar to the PHP sessions default save handler files. This example could easily be extended to cover database storage using your favorite PHP supported database engine. // Note we use the OOP prototype with session_set_save_handler() and register the shutdown function using the function's parameter flag. This is generally advised when registering objects as session save handlers. // Caution: For brevity, this example omits input validation. However, the $id parameters are actually user supplied values which require proper validation/sanitization to avoid vulnerabilities, such as path traversal issues. So do not use this example unmodified in production environments. // [php] // class MySessionHandler implements SessionHandlerInterface // { // private $savePath; // // public function open($savePath, $sessionName): bool // { // $this->savePath = $savePath; // if (!is_dir($this->savePath)) { // mkdir($this->savePath, 0777); // } // // return true; // } // // public function close(): bool // { // return true; // } // // #[\ReturnTypeWillChange] // public function read($id) // { // return (string)@file_get_contents("$this->savePath/sess_$id"); // } // // public function write($id, $data): bool // { // return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true; // } // // public function destroy($id): bool // { // $file = "$this->savePath/sess_$id"; // if (file_exists($file)) { // unlink($file); // } // // return true; // } // // #[\ReturnTypeWillChange] // public function gc($maxlifetime) // { // foreach (glob("$this->savePath/sess_*") as $file) { // if (filemtime($file) + $maxlifetime < time() && file_exists($file)) { // unlink($file); // } // } // // return true; // } // } // // $handler = new MySessionHandler(); // session_set_save_handler($handler, true); // session_start(); // // // proceed to set and retrieve values by key from $_SESSION // [/php] // [/example] // // Table of Contents // * SessionHandlerInterface::close - Close the session // * SessionHandlerInterface::destroy - Destroy a session // * SessionHandlerInterface::gc - Cleanup old sessions // * SessionHandlerInterface::open - Initialize session // * SessionHandlerInterface::read - Read session data // * SessionHandlerInterface::write - Write session data // // LITERATURE_SOURCES // * PHP_NET (2023-11-11) // URL: https://www.php.net/manual/en/class.sessionhandlerinterface.php // THE_SESSIONHANDLERINTERFACE_CLASS - END // // THE_SESSIONIDINTERFACE_INTERFACE - BEGIN // The SessionIdInterface interface // // PHP_5 >= PHP_5_5_1, PHP_7, PHP_8 // // Introduction // SessionIdInterface is an interface which defines optional methods for creating a custom session handler. In order to pass a custom session handler to session_set_save_handler() using its OOP invocation, the class can implement this interface. // Note that the callback methods of classes implementing this interface are designed to be called internally by PHP and are not meant to be called from user-space code. // // Interface synopsis // [code] // interface SessionIdInterface { // // /* Methods */ // public create_sid(): string // } // [/code] // // Table of Contents // * SessionIdInterface::create_sid - Create session ID // // LITERATURE_SOURCES // * PHP_NET (2023-11-11) // URL: https://www.php.net/manual/en/class.sessionidinterface.php // THE_SESSIONIDINTERFACE_INTERFACE - END // // THE_SESSIONUPDATETIMESTAMPHANDLERINTERFACE_INTERFACE - BEGIN // The SessionUpdateTimestampHandlerInterface interface // // PHP_7, PHP_8 // // Introduction // SessionUpdateTimestampHandlerInterface is an interface which defines optional methods for creating a custom session handler. In order to pass a custom session handler to session_set_save_handler() using its OOP invocation, the class can implement this interface. // Note that the callback methods of classes implementing this interface are designed to be called internally by PHP and are not meant to be called from user-space code. // // Class synopsis // [code] // interface SessionUpdateTimestampHandlerInterface { // // /* Methods */ // public updateTimestamp(string $id, string $data): bool // public validateId(string $id): bool // } // [/code] // // Table of Contents // * SessionUpdateTimestampHandlerInterface::updateTimestamp - Update timestamp // * SessionUpdateTimestampHandlerInterface::validateId - Validate ID // // LITERATURE_SOURCES // * PHP_NET (2023-11-11) // URL: https://www.php.net/manual/en/class.sessionupdatetimestamphandlerinterface.php // THE_SESSIONUPDATETIMESTAMPHANDLERINTERFACE_INTERFACE - END // // LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/book.session.php // SESSION_HANDLING - END // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_VARIABLE // ============================== PUBLIC // ============================== ABOUT // Session variables. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING VARIABLES (1) // $_SESSION - PHP_4 >= 4_1_0, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_variable() { $return_session_array = null; // ========== _SESSION - BEGIN // ===== ABOUT // Session variables // ===== DESCRIPTION // An associative array containing session variables available to the current script. See the Session functions documentation for more information on how this is used. // ===== SUPPORTED // PHP_4 >= 4_1_0, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // ===== CODE $return_session_array = $_SESSION; // Notes // Note: This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods. // ===== LITERATURE_SOURCES // * PHP_NET (2023-07-23) // URL: https://www.php.net/manual/en/reserved.variables.session.php // ========== _SESSION - END // SYNTAX: // array $_SESSION return $return_session_array; // array } // ============================== END // PHP_SESSION_SESSIONS_SESSION_VARIABLE // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_ABORT // ============================== OFFLINE // ============================== ABOUT // Discard session array changes and finish session. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // session_abort() - PHP_5 >= PHP_5_6_0, PHP_7, PHP_8 // ============================== CODE /* function php_session_sessions_session_abort() { $return_session_abort = false; // ========== SESSION_ABORT - BEGIN // ===== ABOUT // Discard session array changes and finish session // ===== DESCRIPTION // session_abort() finishes session without saving data. Thus the original values in session data are kept. // ===== SUPPORTED // PHP_5 >= PHP_5_6_0, PHP_7, PHP_8 // ===== SYNTAX // session_abort(): bool // ===== CODE $return_session_abort = session_abort( // This function has no parameters. ); // Return Values // Returns true on success or false on failure. // // Changelog // Version - Description // 7.2.0 - The return type of this function is bool now. Formerly, it has been void. // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-08) // URL: https://www.php.net/manual/en/function.session-abort.php // ========== SESSION_ABORT - END // SYNTAX: // bool session_abort() return $return_session_abort; // bool } */ // ============================== END // PHP_SESSION_SESSIONS_SESSION_ABORT // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_CACHE_EXPIRE // ============================== PUBLIC // ============================== ABOUT // Get and/or set current cache expire. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_cache_expire() - PHP_4 >= PHP_4_2_0, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_cache_expire($value = null) { $return_session_cache_expire = false; // ========== SESSION_CACHE_EXPIRE - BEGIN // ===== ABOUT // Get and/or set current cache expire // ===== DESCRIPTION // session_cache_expire() returns the current setting of session.cache_expire. // The cache expire is reset to the default value of 180 stored in session.cache_expire at request startup time. Thus, you need to call session_cache_expire() for every request (and before session_start() is called). // ===== SUPPORTED // PHP_4 >= PHP_4_2_0, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_cache_expire(?int $value = null): int|false // ===== CODE $return_session_cache_expire = session_cache_expire( $value // int value - If value is given and not null, the current cache expire is replaced with value. // Note: Setting value is of value only, if session.cache_limiter is set to a value different from nocache. ); // Return Values // Returns the current setting of session.cache_expire. The value returned should be read in minutes, defaults to 180. On failure to change the value, false is returned. // // Changelog // Version - Description // 8.0.0 - value is nullable now. // // [examples] // Examples // [example] // Example #1 session_cache_expire() example // [php] // // // set the cache limiter to 'private' // // session_cache_limiter('private'); // $cache_limiter = session_cache_limiter(); // // // set the cache expire to 30 minutes // session_cache_expire(30); // $cache_expire = session_cache_expire(); // // // start the session // // session_start(); // // echo "The cache limiter is now set to $cache_limiter