= 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
"; // echo "The cached session pages expire after $cache_expire minutes"; // [/php] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-15) // URL: https://www.php.net/manual/en/function.session-cache-expire.php // ========== SESSION_CACHE_EXPIRE - END // SYNTAX: // int|false session_cache_expire(int $value = null) return $return_session_cache_expire; // int|false } // ============================== END // PHP_SESSION_SESSIONS_SESSION_CACHE_EXPIRE // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_CACHE_LIMITER // ============================== PUBLIC // ============================== ABOUT // Get and/or set the current cache limiter. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_cache_limiter() - PHP_4 >= PHP_4_0_3, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_cache_limiter($value = null) { $return_session_cache_limiter = false; // ========== SESSION_CACHE_LIMITER - BEGIN // ===== ABOUT // Get and/or set the current cache limiter // ===== DESCRIPTION // session_cache_limiter() returns the name of the current cache limiter. // The cache limiter defines which cache control HTTP headers are sent to the client. These headers determine the rules by which the page content may be cached by the client and intermediate proxies. Setting the cache limiter to nocache disallows any client/proxy caching. A value of public permits caching by proxies and the client, whereas private disallows caching by proxies and permits the client to cache the contents. // In private mode, the Expire header sent to the client may cause confusion for some browsers, including Mozilla. You can avoid this problem by using private_no_expire mode. The Expire header is never sent to the client in this mode. // Setting the cache limiter to '' will turn off automatic sending of cache headers entirely. // The cache limiter is reset to the default value stored in session.cache_limiter at request startup time. Thus, you need to call session_cache_limiter() for every request (and before session_start() is called). // ===== SUPPORTED // PHP_4 >= PHP_4_0_3, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_cache_limiter(?string $value = null): string|false // ===== CODE $return_session_cache_limiter = session_cache_limiter( $value // string value - If value is specified and not null, the name of the current cache limiter is changed to the new value. // // Possible values // Value - Headers sent // * public - // Expires: (sometime in the future, according session.cache_expire) // Cache-Control: public, max-age=(sometime in the future, according to session.cache_expire) // Last-Modified: (the timestamp of when the session was last saved) // * private_no_expire - // Cache-Control: private, max-age=(session.cache_expire in the future), pre-check=(session.cache_expire in the future) // Last-Modified: (the timestamp of when the session was last saved) // * private - // Expires: Thu, 19 Nov 1981 08:52:00 GMT // Cache-Control: private, max-age=(session.cache_expire in the future), pre-check=(session.cache_expire in the future) // Last-Modified: (the timestamp of when the session was last saved) // * nocache - // Expires: Thu, 19 Nov 1981 08:52:00 GMT // Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 // Pragma: no-cache ); // Return Values // Returns the name of the current cache limiter. 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_limiter() example // [php] // // // set the cache limiter to 'private' // // session_cache_limiter('private'); // $cache_limiter = session_cache_limiter(); // // echo "The cache limiter is now set to $cache_limiter
"; // [/php] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-15) // URL: https://www.php.net/manual/en/function.session-cache-limiter.php // ========== SESSION_CACHE_LIMITER - END // SYNTAX: // string|false session_cache_limiter(string $value = null) return $return_session_cache_limiter; // string|false } // ============================== END // PHP_SESSION_SESSIONS_SESSION_CACHE_LIMITER // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_COMMIT // ============================== PUBLIC // ============================== ABOUT // Write session data and end session. // // session_commit - Alias of session_write_close() // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_commit() - PHP_4 >= PHP_4_4_0, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_commit() { $return_session_commit = false; // ========== SESSION_COMMIT - BEGIN // ===== ABOUT // session_commit - Alias of session_write_close() // ===== DESCRIPTION // This function is an alias of: session_write_close(). // ===== SUPPORTED // PHP_4 >= PHP_4_4_0, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // ===== CODE $return_session_commit = session_commit( // This function has no parameters. ); // Return // bool // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-15) // URL: https://www.php.net/manual/en/function.session-commit.php // ========== SESSION_COMMIT - END // ========== SESSION_WRITE_CLOSE - BEGIN // ===== ABOUT // Write session data and end session // ===== DESCRIPTION // End the current session and store session data. // Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done. // ===== SUPPORTED // PHP_4 >= PHP_4_0_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_write_close(): bool // ===== CODE // $return_session_write_close = session_write_close( // 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-09) // URL: https://www.php.net/manual/en/function.session-write-close.php // ========== SESSION_WRITE_CLOSE - END // SYNTAX: // bool session_commit() return $return_session_commit; // bool } // ============================== END // PHP_SESSION_SESSIONS_SESSION_COMMIT // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_CREATE_ID // ============================== OFFLINE // ============================== ABOUT // Create new session id. // ============================== SUPPORT // PHP_7 - PHP_8 // ============================== USING FUNCTIONS (1) // session_create_id() - PHP_7 >= PHP_7_1_0, PHP_8 // ============================== CODE /* function php_session_sessions_session_create_id($prefix = "") { $return_session_create_id = false; // ========== SESSION_CREATE_ID - BEGIN // ===== ABOUT // Create new session id // ===== DESCRIPTION // session_create_id() is used to create new session id for the current session. It returns collision free session id. // If session is not active, collision check is omitted. // Session ID is created according to php.ini settings. // It is important to use the same user ID of your web server for GC task script. Otherwise, you may have permission problems especially with files save handler. // ===== SUPPORTED // PHP_7 >= PHP_7_1_0, PHP_8 // ===== SYNTAX // session_create_id(string $prefix = ""): string|false // ===== CODE $return_session_create_id = session_create_id( $prefix // string prefix - If prefix is specified, new session id is prefixed by prefix. Not all characters are allowed within the session id. Characters in the range a-z A-Z 0-9 , (comma) and - (minus) are allowed. ); // Return Values // session_create_id() returns new collision free session id for the current session. If it is used without active session, it omits collision check. On failure, false is returned. // // [examples] // Examples // [example] // Example #1 session_create_id() example with session_regenerate_id() // [php] // // My session start function support timestamp management // function my_session_start() { // session_start(); // // Do not allow to use too old session ID // if (!empty($_SESSION['deleted_time']) && $_SESSION['deleted_time'] < time() - 180) { // session_destroy(); // session_start(); // } // } // // // My session regenerate id function function my_session_regenerate_id() { // // Call session_create_id() while session is active to // // make sure collision free. // if (session_status() != PHP_SESSION_ACTIVE) { // session_start(); // } // // WARNING: Never use confidential strings for prefix! // $newid = session_create_id('myprefix-'); // // Set deleted timestamp. Session data must not be deleted immediately for reasons. // $_SESSION['deleted_time'] = time(); // // Finish session // session_commit(); // // Make sure to accept user defined session ID // // NOTE: You must enable use_strict_mode for normal operations. // ini_set('session.use_strict_mode', 0); // // Set new custom session ID // session_id($newid); // // Start with custom session ID // session_start(); // } // // // Make sure use_strict_mode is enabled. // // use_strict_mode is mandatory for security reasons. // ini_set('session.use_strict_mode', 1); // my_session_start(); // // // Session ID must be regenerated when // // - User logged in // // - User logged out // // - Certain period has passed // my_session_regenerate_id(); // // // Write useful codes // [/php] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-15) // URL: https://www.php.net/manual/en/function.session-create-id.php // ========== SESSION_CREATE_ID - END // SYNTAX: // string|false session_create_id(string $prefix = "") return $return_session_create_id; // string|false } */ // ============================== END // PHP_SESSION_SESSIONS_SESSION_CREATE_ID // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_DECODE // ============================== PUBLIC // ============================== ABOUT // Decodes session data from a session encoded string. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_decode() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_decode($data) { $return_session_decode = false; // ========== SESSION_DECODE - BEGIN // ===== ABOUT // Decodes session data from a session encoded string // ===== DESCRIPTION // session_decode() decodes the serialized session data provided in $data, and populates the $_SESSION superglobal with the result. // By default, the unserialization method used is internal to PHP, and is not the same as unserialize(). The serialization method can be set using session.serialize_handler. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_decode(string $data): bool // ===== CODE $return_session_decode = session_decode( $data // string data - The encoded data to be stored. ); // Return Values // Returns true on success or false on failure. // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-09) // URL: https://www.php.net/manual/en/function.session-decode.php // ========== SESSION_DECODE - END // SYNTAX: // bool session_decode(string $data) return $return_session_decode; // bool } // ============================== END // PHP_SESSION_SESSIONS_SESSION_DECODE // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_DESTROY // ============================== PUBLIC // ============================== ABOUT // Destroys all data registered to a session. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_destroy() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_destroy() { $return_session_destroy = false; // ========== SESSION_DESTROY - BEGIN // ===== ABOUT // Destroys all data registered to a session // ===== DESCRIPTION // session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called. // Note: You do not have to call session_destroy() from usual code. Cleanup $_SESSION array rather than destroying session data. // In order to kill the session altogether, the session ID must also be unset. If a cookie is used to propagate the session ID (default behavior), then the session cookie must be deleted. setcookie() may be used for that. // When session.use_strict_mode is enabled. You do not have to remove obsolete session ID cookie because session module will not accept session ID cookie when there is no data associated to the session ID and set new session ID cookie. Enabling session.use_strict_mode is recommended for all sites. // Warning: Immediate session deletion may cause unwanted results. When there is concurrent requests, other connections may see sudden session data loss. e.g. Requests from JavaScript and/or requests from URL links. // Although current session module does not accept empty session ID cookie, but immediate session deletion may result in empty session ID cookie due to client(browser) side race condition. This will result that the client creates many session ID needlessly. // To avoid these, you must set deletion time-stamp to $_SESSION and reject access while later. Or make sure your application does not have concurrent requests. This applies to session_regenerate_id() also. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_destroy(): bool // ===== CODE $return_session_destroy = session_destroy( // This function has no parameters. ); // Return Values // Returns true on success or false on failure. // // [examples] // Examples // [example] // Example #1 Destroying a session with $_SESSION // [php] // // Initialize the session. // // If you are using session_name("something"), don't forget it now! // session_start(); // // // Unset all of the session variables. // $_SESSION = array(); // // // If it's desired to kill the session, also delete the session cookie. // // Note: This will destroy the session, and not just the session data! // if (ini_get("session.use_cookies")) { // $params = session_get_cookie_params(); // setcookie(session_name(), '', time() - 42000, // $params["path"], $params["domain"], // $params["secure"], $params["httponly"] // ); // } // // // Finally, destroy the session. // session_destroy(); // [/php] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-14) // URL: https://www.php.net/manual/en/function.session-destroy.php // ========== SESSION_DESTROY - END // SYNTAX: // bool session_destroy() return $return_session_destroy; // bool } // ============================== END // PHP_SESSION_SESSIONS_SESSION_DESTROY // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_ENCODE // ============================== PUBLIC // ============================== ABOUT // Encodes the current session data as a session encoded string. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_encode() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_encode() { $return_session_encode = false; // ========== SESSION_ENCODE - BEGIN // ===== ABOUT // Encodes the current session data as a session encoded string // ===== DESCRIPTION // session_encode() returns a serialized string of the contents of the current session data stored in the $_SESSION superglobal. // By default, the serialization method used is internal to PHP, and is not the same as serialize(). The serialization method can be set using session.serialize_handler. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_encode(): string|false // ===== CODE $return_session_encode = session_encode( // This function has no parameters. ); // Return Values // Returns the contents of the current session encoded, or false on failure. // // Notes // Warning: Must call session_start() before using session_encode(). // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-09) // URL: https://www.php.net/manual/en/function.session-encode.php // ========== SESSION_ENCODE - END // SYNTAX: // string|false session_encode() return $return_session_encode; // string|false } // ============================== END // PHP_SESSION_SESSIONS_SESSION_ENCODE // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_GC // ============================== OFFLINE // ============================== ABOUT // Perform session data garbage collection. // ============================== SUPPORT // PHP_7 - PHP_8 // ============================== USING FUNCTIONS (1) // session_gc() - PHP_7 >= PHP_7_1_0, PHP_8 // ============================== CODE /* function php_session_sessions_session_gc() { $return_session_gc = false; // ========== SESSION_GC - BEGIN // ===== ABOUT // Perform session data garbage collection // ===== DESCRIPTION // session_gc() is used to perform session data GC(garbage collection). PHP does probability based session GC by default. // Probability based GC works somewhat but it has few problems. 1) Low traffic sites' session data may not be deleted within the preferred duration. 2) High traffic sites' GC may be too frequent GC. 3) GC is performed on the user's request and the user will experience a GC delay. // Therefore, it is recommended to execute GC periodically for production systems using, e.g., "cron" for UNIX-like systems. Make sure to disable probability based GC by setting session.gc_probability to 0. // ===== SUPPORTED // PHP_7 >= PHP_7_1_0, PHP_8 // ===== SYNTAX // session_gc(): int|false // ===== CODE $return_session_gc = session_gc( // This function has no parameters. ); // Return Values // session_gc() returns number of deleted session data for success, false for failure. // Old save handlers do not return number of deleted session data, but only success/failure flag. If this is the case, number of deleted session data became 1 regardless of actually deleted data. // // [examples] // Examples // [example] // Example #1 session_gc() example for task managers like cron // [php] // // Note: This script should be executed by the same user of web server process. // // // Need active session to initialize session data storage access. // session_start(); // // // Executes GC immediately // session_gc(); // // // Clean up session ID created by session_gc() // session_destroy(); // [/php] // [/example] // [example] // Example #2 session_gc() example for user accessible script // [php] // // Note: session_gc() is recommended to be used by task manager script, but // // it may be used as follows. // // // Used for last GC time check // $gc_time = '/tmp/php_session_last_gc'; // $gc_period = 1800; // // session_start(); // // Execute GC only when GC period elapsed. // // i.e. Calling session_gc() every request is waste of resources. // if (file_exists($gc_time)) { // if (filemtime($gc_time) < time() - $gc_period) { // session_gc(); // touch($gc_time); // } // } else { // touch($gc_time); // } // [/php] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-15) // URL: https://www.php.net/manual/en/function.session-gc.php // ========== SESSION_GC - END // SYNTAX: // int|false session_gc() return $return_session_gc; // int|false } */ // ============================== END // PHP_SESSION_SESSIONS_SESSION_GC // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_GET_COOKIE_PARAMS // ============================== PUBLIC // ============================== ABOUT // Get the session cookie parameters. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_get_cookie_params() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_get_cookie_params() { $return_session_get_cookie_params = null; // ========== SESSION_GET_COOKIE_PARAMS - BEGIN // ===== ABOUT // Get the session cookie parameters // ===== DESCRIPTION // Gets the session cookie parameters. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_get_cookie_params(): array // ===== CODE $return_session_get_cookie_params = session_get_cookie_params( // This function has no parameters. ); // Return Values // Returns an array with the current session cookie information, the array contains the following items: // * "lifetime" - The lifetime of the cookie in seconds. // * "path" - The path where information is stored. // * "domain" - The domain of the cookie. // * "secure" - The cookie should only be sent over secure connections. // * "httponly" - The cookie can only be accessed through the HTTP protocol. // * "samesite" - Controls the cross-domain sending of the cookie. // // Changelog // Version - Description // 7.3.0 - The "samesite" entry was added in the returned array. // ===== LITERATURE_SOURCES // * PHP_NET (2023-07-23) // URL: https://www.php.net/manual/en/function.session-get-cookie-params.php // ========== SESSION_GET_COOKIE_PARAMS - END // SYNTAX: // array session_get_cookie_params() return $return_session_get_cookie_params; // array } // ============================== END // PHP_SESSION_SESSIONS_SESSION_GET_COOKIE_PARAMS // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_ID // ============================== PUBLIC // ============================== ABOUT // Get and/or set the current session id. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_id() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_id($id = null) { $return_session_id = false; // ========== SESSION_ID - BEGIN // ===== ABOUT // Get and/or set the current session id. // ===== DESCRIPTION // session_id() is used to get or set the session id for the current session. // The constant SID can also be used to retrieve the current name and session id as a string suitable for adding to URLs. See also Session handling. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_id(?string $id = null): string|false // ===== CODE $return_session_id = session_id( $id // string id - If id is specified and not null, it will replace the current session id. session_id() needs to be called before session_start() for that purpose. Depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z A-Z 0-9 , (comma) and - (minus)! // Note: When using session cookies, specifying an id for session_id() will always send a new cookie when session_start() is called, regardless if the current session id is identical to the one being set. ); // Return Values // session_id() returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists). On failure, false is returned. // // Changelog // Version - Description // 8.0.0 - id is nullable now. // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-09) // URL: https://www.php.net/manual/en/function.session-id.php // ========== SESSION_ID - END // SYNTAX: // string|false session_id(string $id = null) return $return_session_id; // string|false } // ============================== END // PHP_SESSION_SESSIONS_SESSION_ID // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_MODULE_NAME // ============================== PUBLIC // ============================== ABOUT // Get and/or set the current session module. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_module_name() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_module_name($module = null) { $return_session_module_name = false; // ========== SESSION_MODULE_NAME - BEGIN // ===== ABOUT // Get and/or set the current session module // ===== DESCRIPTION // session_module_name() gets the name of the current session module, which is also known as session.save_handler. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_module_name(?string $module = null): string|false // ===== CODE $return_session_module_name = session_module_name( $module // string module - If module is specified and not null, that module will be used instead. Passing "user" to this parameter is forbidden. Instead session_set_save_handler() has to be called to set a user defined session handler. ); // Return Values // Returns the name of the current session module, or false on failure. // // Changelog // Version - Description // 8.0.0 - module is nullable now. // 7.2.0 - It is now explicitly forbidden to set the module name to "user". Formerly, this has been silently ignored. // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-09) // URL: https://www.php.net/manual/en/function.session-module-name.php // ========== SESSION_MODULE_NAME - END // SYNTAX: // string|false session_module_name(string $module = null) return $return_session_module_name; // string|false } // ============================== END // PHP_SESSION_SESSIONS_SESSION_MODULE_NAME // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_NAME // ============================== PUBLIC // ============================== ABOUT // Get and/or set the current session name. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_name() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_name($name = null) { $return_session_name = false; // ========== SESSION_NAME - BEGIN // ===== ABOUT // Get and/or set the current session name // ===== DESCRIPTION // session_name() returns the name of the current session. If name is given, session_name() will update the session name and return the old session name. // If a new session name is supplied, session_name() modifies the HTTP cookie (and output content when session.transid is enabled). Once the HTTP cookie is sent, session_name() raises error. session_name() must be called before session_start() for the session to work properly. // The session name is reset to the default value stored in session.name at request startup time. Thus, you need to call session_name() for every request (and before session_start() is called). // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_name(?string $name = null): string|false // ===== CODE $return_session_name = session_name( $name // string name - The session name references the name of the session, which is used in cookies and URLs (e.g. PHPSESSID). It should contain only alphanumeric characters; it should be short and descriptive (i.e. for users with enabled cookie warnings). If name is specified and not null, the name of the current session is changed to its value. // Warning: The session name can't consist of digits only, at least one letter must be present. Otherwise a new session id is generated every time. ); // Return Values // Returns the name of the current session. If name is given and function updates the session name, name of the old session is returned, or false on failure. // // Changelog // Version - Description // 8.0.0 - name is nullable now. // 7.2.0 - session_name() checks session status, previously it only checked cookie status. Therefore, older session_name() allows to call session_name() after session_start() which may crash PHP and may result in misbehaviors. // // [examples] // Examples // [example] // Example #1 session_name() example // [php] // // // set the session name to WebsiteID // // $previous_name = session_name("WebsiteID"); // // echo "The previous session name was $previous_name
"; // [/php] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-15) // URL: https://www.php.net/manual/en/function.session-name.php // ========== SESSION_NAME - END // SYNTAX: // string|false session_name(string $name = null) return $return_session_name; // string|false } // ============================== END // PHP_SESSION_SESSIONS_SESSION_NAME // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_REGENERATE_ID // ============================== PUBLIC // ============================== ABOUT // Update the current session id with a newly generated one. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_regenerate_id() - PHP_4 >= PHP_4_3_2, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_regenerate_id($delete_old_session = false) { $return_session_regenerate_id = false; // ========== SESSION_REGENERATE_ID - BEGIN // ===== ABOUT // Update the current session id with a newly generated one // ===== DESCRIPTION // session_regenerate_id() will replace the current session id with a new one, and keep the current session information. // When session.use_trans_sid is enabled, output must be started after session_regenerate_id() call. Otherwise, old session ID is used. // Warning: Currently, session_regenerate_id does not handle an unstable network well, e.g. Mobile and WiFi network. Therefore, you may experience a lost session by calling session_regenerate_id. // You should not destroy old session data immediately, but should use destroy time-stamp and control access to old session ID. Otherwise, concurrent access to page may result in inconsistent state, or you may have lost session, or it may cause client(browser) side race condition and may create many session ID needlessly. Immediate session data deletion disables session hijack attack detection and prevention also. // ===== SUPPORTED // PHP_4 >= PHP_4_3_2, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_regenerate_id(bool $delete_old_session = false): bool // ===== CODE $return_session_regenerate_id = session_regenerate_id( $delete_old_session // bool delete_old_session - Whether to delete the old associated session file or not. You should not delete old session if you need to avoid races caused by deletion or detect/avoid session hijack attacks. ); // Return Values // Returns true on success or false on failure. // // [examples] // Examples // [example] // Example #1 A session_regenerate_id() example // [php] // // NOTE: This code is not fully working code, but an example! // // session_start(); // // // Check destroyed time-stamp // if (isset($_SESSION['destroyed']) // && $_SESSION['destroyed'] < time() - 300) { // // Should not happen usually. This could be attack or due to unstable network. // // Remove all authentication status of this users session. // remove_all_authentication_flag_from_active_sessions($_SESSION['userid']); // throw(new DestroyedSessionAccessException); // } // // $old_sessionid = session_id(); // // // Set destroyed timestamp // $_SESSION['destroyed'] = time(); // session_regenerate_id() saves old session data // // // Simply calling session_regenerate_id() may result in lost session, etc. // // See next example. // session_regenerate_id(); // // // New session does not need destroyed timestamp // unset($_SESSION['destroyed']); // // $new_sessionid = session_id(); // // echo "Old Session: $old_sessionid
"; // echo "New Session: $new_sessionid
"; // // print_r($_SESSION); // [/php] // Current session module does not handle unstable network well. You should manage session ID to avoid lost session by session_regenerate_id. // [/example] // [example] // Example #2 Avoiding lost session by session_regenerate_id() // [php] // // NOTE: This code is not fully working code, but an example! // // my_session_start() and my_session_regenerate_id() avoid lost sessions by // // unstable network. In addition, this code may prevent exploiting stolen // // session by attackers. // // function my_session_start() { // session_start(); // if (isset($_SESSION['destroyed'])) { // if ($_SESSION['destroyed'] < time()-300) { // // Should not happen usually. This could be attack or due to unstable network. // // Remove all authentication status of this users session. // remove_all_authentication_flag_from_active_sessions($_SESSION['userid']); // throw(new DestroyedSessionAccessException); // } // if (isset($_SESSION['new_session_id'])) { // // Not fully expired yet. Could be lost cookie by unstable network. // // Try again to set proper session ID cookie. // // NOTE: Do not try to set session ID again if you would like to remove // // authentication flag. // session_commit(); // session_id($_SESSION['new_session_id']); // // New session ID should exist // session_start(); // return; // } // } // } // // function my_session_regenerate_id() { // // New session ID is required to set proper session ID // // when session ID is not set due to unstable network. // $new_session_id = session_create_id(); // $_SESSION['new_session_id'] = $new_session_id; // // // Set destroy timestamp // $_SESSION['destroyed'] = time(); // // // Write and close current session; // session_commit(); // // // Start session with new session ID // session_id($new_session_id); // ini_set('session.use_strict_mode', 0); // session_start(); // ini_set('session.use_strict_mode', 1); // // // New session does not need them // unset($_SESSION['destroyed']); // unset($_SESSION['new_session_id']); // } // [/php] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-15) // URL: https://www.php.net/manual/en/function.session-regenerate-id.php // ========== SESSION_REGENERATE_ID - END // SYNTAX: // bool session_regenerate_id(bool $delete_old_session = false) return $return_session_regenerate_id; // bool } // ============================== END // PHP_SESSION_SESSIONS_SESSION_REGENERATE_ID // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_REGISTER_SHUTDOWN // ============================== OFFLINE // ============================== ABOUT // Session shutdown function. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // session_register_shutdown() - PHP_5 >= PHP_5_4_0, PHP_7, PHP_8 // ============================== CODE /* function php_session_sessions_session_register_shutdown() { // ========== SESSION_REGISTER_SHUTDOWN - BEGIN // ===== ABOUT // Session shutdown function // ===== DESCRIPTION // Registers session_write_close() as a shutdown function. // ===== SUPPORTED // PHP_5 >= PHP_5_4_0, PHP_7, PHP_8 // ===== SYNTAX // session_register_shutdown(): void // ===== CODE session_register_shutdown( // This function has no parameters. ); // Return Values // No value is returned. // // Errors/Exceptions // Emits E_WARNING if registering the shutdown function fails. // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-09) // URL: https://www.php.net/manual/en/function.session-register-shutdown.php // ========== SESSION_REGISTER_SHUTDOWN - END // SYNTAX: // void session_register_shutdown() // Return: void } */ // ============================== END // PHP_SESSION_SESSIONS_SESSION_REGISTER_SHUTDOWN // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_RESET // ============================== OFFLINE // ============================== ABOUT // Re-initialize session array with original values. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // session_reset() - PHP_5 >= PHP_5_6_0, PHP_7, PHP_8 // ============================== CODE /* function php_session_sessions_session_reset() { $return_session_reset = false; // ========== SESSION_RESET - BEGIN // ===== ABOUT // Re-initialize session array with original values // ===== DESCRIPTION // session_reset() reinitializes a session with original values stored in session storage. This function requires an active session and discards changes in $_SESSION. // ===== SUPPORTED // PHP_5 >= PHP_5_6_0, PHP_7, PHP_8 // ===== SYNTAX // session_reset(): bool // ===== CODE $return_session_reset = session_reset( // 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-09) // URL: https://www.php.net/manual/en/function.session-reset.php // ========== SESSION_RESET - END // SYNTAX: // bool session_reset() return $return_session_reset; // bool } */ // ============================== END // PHP_SESSION_SESSIONS_SESSION_RESET // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_SAVE_PATH // ============================== PUBLIC // ============================== ABOUT // Get and/or set the current session save path. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_save_path() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_save_path($path = null) { $return_session_save_path = false; // ========== SESSION_SAVE_PATH - BEGIN // ===== ABOUT // Get and/or set the current session save path // ===== DESCRIPTION // session_save_path() returns the path of the current directory used to save session data. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_save_path(?string $path = null): string|false // ===== CODE $return_session_save_path = session_save_path( $path // string path - Session data path. If specified and not null, the path to which data is saved will be changed. session_save_path() needs to be called before session_start() for that purpose. // Note: On some operating systems, you may want to specify a path on a filesystem that handles lots of small files efficiently. For example, on Linux, reiserfs may provide better performance than ext2fs. ); // Return Values // Returns the path of the current directory used for data storage, or false on failure. // // Changelog // Version - Description // 8.0.0 - path is nullable now. // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-09) // URL: https://www.php.net/manual/en/function.session-save-path.php // ========== SESSION_SAVE_PATH - END // SYNTAX: // string|false session_save_path(string $path = null) return $return_session_save_path; // string|false } // ============================== END // PHP_SESSION_SESSIONS_SESSION_SAVE_PATH // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_SET_COOKIE_PARAMS // ============================== PUBLIC // ============================== ABOUT // Set the session cookie parameters. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_set_cookie_params() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_set_cookie_params($lifetime_or_options, $path = null, $domain = null, $secure = null, $httponly = null) { $return_session_set_cookie_params = false; // ========== SESSION_SET_COOKIE_PARAMS - BEGIN // ===== ABOUT // Set the session cookie parameters // ===== DESCRIPTION // Set cookie parameters defined in the php.ini file. The effect of this function only lasts for the duration of the script. Thus, you need to call session_set_cookie_params() for every request and before session_start() is called. // This function updates the runtime ini values of the corresponding PHP ini configuration keys which can be retrieved with the ini_get(). // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_set_cookie_params( // int $lifetime_or_options, // ?string $path = null, // ?string $domain = null, // ?bool $secure = null, // ?bool $httponly = null // ): bool // // Alternative signature available as of PHP 7.3.0: // session_set_cookie_params(array $lifetime_or_options): bool // ===== CODE $return_session_set_cookie_params = session_set_cookie_params( $lifetime_or_options, // int lifetime_or_options - When using the first signature, lifetime of the session cookie, defined in seconds. // When using the second signature, an associative array which may have any of the keys lifetime, path, domain, secure, httponly and samesite. The values have the same meaning as described for the parameters with the same name. The value of the samesite element should be either Lax or Strict. If any of the allowed options are not given, their default values are the same as the default values of the explicit parameters. If the samesite element is omitted, no SameSite cookie attribute is set. $path, // string path - Path on the domain where the cookie will work. Use a single slash ('/') for all paths on the domain. $domain, // string domain - Cookie domain, for example 'www.php.net'. To make cookies visible on all subdomains then the domain must be prefixed with a dot like '.php.net'. $secure, // bool secure - If true cookie will only be sent over secure connections. $httponly // bool httponly - If set to true then PHP will attempt to send the httponly flag when setting the session cookie. ); // Return Values // Returns true on success or false on failure. // // Changelog // Version - Description // 8.0.0 - path, domain, secure and httponly are nullable now. // 7.3.0 - An alternative signature supporting an lifetime_or_options array has been added. This signature supports also setting of the SameSite cookie attribute. // 7.2.0 - Returns true on success or false on failure. Formerly the function returned void. // ===== LITERATURE_SOURCES // * PHP_NET (2023-07-23) // URL: https://www.php.net/manual/en/function.session-set-cookie-params.php // ========== SESSION_SET_COOKIE_PARAMS - END // SYNTAX: // bool session_set_cookie_params(int $lifetime_or_options, string $path = null, string $domain = null, bool $secure = null, bool $httponly = null) return $return_session_set_cookie_params; // bool } // ============================== END // PHP_SESSION_SESSIONS_SESSION_SET_COOKIE_PARAMS // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_SET_SAVE_HANDLER // ============================== PUBLIC // ============================== ABOUT // Sets user-level session storage functions. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_set_save_handler() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_set_save_handler($sessionhandler, $register_shutdown = true) { $return_session_set_save_handler = false; // ========== SESSION_SET_SAVE_HANDLER - BEGIN // ===== ABOUT // Sets user-level session storage functions // ===== DESCRIPTION // session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred, e.g. storing the session data in a local database. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_set_save_handler( // callable $open, // callable $close, // callable $read, // callable $write, // callable $destroy, // callable $gc, // callable $create_sid = ?, // callable $validate_sid = ?, // callable $update_timestamp = ? // ): bool // // It is possible to register the following prototype: // session_set_save_handler(object $sessionhandler, bool $register_shutdown = true): bool // ===== CODE $return_session_set_save_handler = session_set_save_handler( // This function has two prototypes. $sessionhandler, // object sessionhandler - An instance of a class implementing SessionHandlerInterface, and optionally SessionIdInterface and/or SessionUpdateTimestampHandlerInterface, such as SessionHandler, to register as the session handler. $register_shutdown // bool register_shutdown - Register session_write_close() as a register_shutdown_function() function. // or // callable open - A callable with the following signature: // open(string $savePath, string $sessionName): bool // The open callback works like a constructor in classes and is executed when the session is being opened. It is the first callback function executed when the session is started automatically or manually with session_start(). Return value is true for success, false for failure. // callable close - A callable with the following signature: // close(): bool // The close callback works like a destructor in classes and is executed after the session write callback has been called. It is also invoked when session_write_close() is called. Return value should be true for success, false for failure. // callable read - A callable with the following signature: // read(string $sessionId): string // The read callback must always return a session encoded (serialized) string, or an empty string if there is no data to read. // This callback is called internally by PHP when the session starts or when session_start() is called. Before this callback is invoked PHP will invoke the open callback. // The value this callback returns must be in exactly the same serialized format that was originally passed for storage to the write callback. The value returned will be unserialized automatically by PHP and used to populate the $_SESSION superglobal. While the data looks similar to serialize() please note it is a different format which is specified in the session.serialize_handler ini setting. // callable write - A callable with the following signature: // write(string $sessionId, string $data): bool // The write callback is called when the session needs to be saved and closed. This callback receives the current session ID a serialized version the $_SESSION superglobal. The serialization method used internally by PHP is specified in the session.serialize_handler ini setting. // The serialized session data passed to this callback should be stored against the passed session ID. When retrieving this data, the read callback must return the exact value that was originally passed to the write callback. // This callback is invoked when PHP shuts down or explicitly when session_write_close() is called. Note that after executing this function PHP will internally execute the close callback. // Note: The "write" handler is not executed until after the output stream is closed. Thus, output from debugging statements in the "write" handler will never be seen in the browser. If debugging output is necessary, it is suggested that the debug output be written to a file instead. // callable destroy - A callable with the following signature: // destroy(string $sessionId): bool // This callback is executed when a session is destroyed with session_destroy() or with session_regenerate_id() with the destroy parameter set to true. Return value should be true for success, false for failure. // callable gc - A callable with the following signature: // gc(int $lifetime): bool // The garbage collector callback is invoked internally by PHP periodically in order to purge old session data. The frequency is controlled by session.gc_probability and session.gc_divisor. The value of lifetime which is passed to this callback can be set in session.gc_maxlifetime. Return value should be true for success, false for failure. // callable create_sid - A callable with the following signature: // create_sid(): string // This callback is executed when a new session ID is required. No parameters are provided, and the return value should be a string that is a valid session ID for your handler. // callable validate_sid - A callable with the following signature: // validate_sid(string $key): bool // This callback is executed when a session is to be started, a session ID is supplied and session.use_strict_mode is enabled. The key is the session ID to validate. A session ID is valid, if a session with that ID already exists. The return value should be true for success, false for failure. // callable update_timestamp - A callable with the following signature: // update_timestamp(string $key, string $val): bool // This callback is executed when a session is updated. key is the session ID, val is the session data. The return value should be true for success, false for failure. ); // Return Values // Returns true on success or false on failure. // // [examples] // Examples // [example] // Example #1 Custom session handler: see full code in SessionHandlerInterface synopsis. // We just show the invocation here, the full example can be seen in the SessionHandlerInterface synopsis linked above. // 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. // [php] // class MySessionHandler implements SessionHandlerInterface // { // // implement interfaces here // } // // $handler = new MySessionHandler(); // session_set_save_handler($handler, true); // session_start(); // // // proceed to set and retrieve values by key from $_SESSION // [/php] // [/example] // [/examples] // // Notes // Warning: The write and close handlers are called after object destruction and therefore cannot use objects or throw exceptions. Exceptions are not able to be caught since will not be caught nor will any exception trace be displayed and the execution will just cease unexpectedly. The object destructors can however use sessions. // It is possible to call session_write_close() from the destructor to solve this chicken and egg problem but the most reliable way is to register the shutdown function as described above. // Warning: Current working directory is changed with some SAPIs if session is closed in the script termination. It is possible to close the session earlier with session_write_close(). // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-15) // URL: https://www.php.net/manual/en/function.session-set-save-handler.php // ========== SESSION_SET_SAVE_HANDLER - END // SYNTAX: // bool session_set_save_handler(object $sessionhandler, bool $register_shutdown = true) return $return_session_set_save_handler; // bool } // ============================== END // PHP_SESSION_SESSIONS_SESSION_SET_SAVE_HANDLER // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_START // ============================== PUBLIC // ============================== ABOUT // Start new or resume existing session. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_start() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_start($options = array()) { $return_session_started = false; // ========== SESSION_START - BEGIN // ===== ABOUT // Start new or resume existing session // ===== DESCRIPTION // session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie. // When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers. These will either be a built-in save handler provided by default or by PHP extensions (such as SQLite or Memcached); or can be custom handler as defined by session_set_save_handler(). The read callback will retrieve any existing session data (stored in a special serialized format) and will be unserialized and used to automatically populate the $_SESSION superglobal when the read callback returns the saved session data back to PHP session handling. // To use a named session, call session_name() before calling session_start(). // When session.use_trans_sid is enabled, the session_start() function will register an internal output handler for URL rewriting. // If a user uses ob_gzhandler or similar with ob_start(), the function order is important for proper output. For example, ob_gzhandler must be registered before starting the session. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_start(array $options = []): bool // ===== CODE $return_session_started = session_start( $options // array options - If provided, this is an associative array of options that will override the currently set session configuration directives. The keys should not include the session. prefix. // In addition to the normal set of configuration directives, a read_and_close option may also be provided. If set to true, this will result in the session being closed immediately after being read, thereby avoiding unnecessary locking if the session data won't be changed. ); // Return Values // This function returns true if a session was successfully started, otherwise false. // // Changelog // Version - Description // 7.1.0 - session_start() now returns false and no longer initializes $_SESSION when it failed to start the session. // // [examples] // Examples // [example] // A basic session example // Example #1 page1.php // [php] // // page1.php // // session_start(); // // echo 'Welcome to page #1'; // // $_SESSION['favcolor'] = 'green'; // $_SESSION['animal'] = 'cat'; // $_SESSION['time'] = time(); // // // Works if session cookie was accepted // echo '
page 2'; // // // Or maybe pass along the session id, if needed // echo '
page 2'; // [/php] // After viewing page1.php, the second page page2.php will magically contain the session data. Read the session reference for information on propagating session ids as it, for example, explains what the constant SID is all about. // [/example] // [example] // Example #2 page2.php // [php] // // page2.php // // session_start(); // // echo 'Welcome to page #2
'; // // echo $_SESSION['favcolor']; // green // echo $_SESSION['animal']; // cat // echo date('Y m d H:i:s', $_SESSION['time']); // // // You may want to use SID here, like we did in page1.php // echo '
page 1'; // [/php] // [/example] // [example] // Providing options to session_start() // Example #3 Overriding the cookie lifetime // [php] // // This sends a persistent cookie that lasts a day. // session_start([ // 'cookie_lifetime' => 86400, // ]); // [/php] // [/example] // [example] // Example #4 Reading the session and closing it // [php] // // If we know we don't need to change anything in the // // session, we can just read and close rightaway to avoid // // locking the session file and blocking other pages // session_start([ // 'cookie_lifetime' => 86400, // 'read_and_close' => true, // ]); // [/php] // [/example] // [/examples] // // Notes // Note: To use cookie-based sessions, session_start() must be called before outputting anything to the browser. // Note: Use of zlib.output_compression is recommended instead of ob_gzhandler() // Note: This function sends out several HTTP headers depending on the configuration. See session_cache_limiter() to customize these headers. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-15) // URL: https://www.php.net/manual/en/function.session-start.php // ========== SESSION_START - END // SYNTAX: // bool session_start(array $options = array()) return $return_session_started; // bool } // ============================== END // PHP_SESSION_SESSIONS_SESSION_START // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_STATUS // ============================== PUBLIC // ============================== ABOUT // Returns the current session status. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // session_status() - PHP_5 >= PHP_5_4_0, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_status() { $return_session_status = 0; // ========== SESSION_STATUS - BEGIN // ===== ABOUT // Returns the current session status // ===== DESCRIPTION // session_status() is used to return the current session status. // ===== SUPPORTED // PHP_5 >= PHP_5_4_0, PHP_7, PHP_8 // ===== SYNTAX // session_status(): int // ===== CODE $return_session_status = session_status( // This function has no parameters. ); // Return Values // * PHP_SESSION_DISABLED - if sessions are disabled. // * PHP_SESSION_NONE - if sessions are enabled, but none exists. // * PHP_SESSION_ACTIVE - if sessions are enabled, and one exists. // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-09) // URL: https://www.php.net/manual/en/function.session-status.php // ========== SESSION_STATUS - END // SYNTAX: // int session_status() return $return_session_status; // int } // ============================== END // PHP_SESSION_SESSIONS_SESSION_STATUS // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_UNSET // ============================== PUBLIC // ============================== ABOUT // Free all session variables. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_unset() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_unset() { $return_session_unset = false; // ========== SESSION_UNSET - BEGIN // ===== ABOUT // Free all session variables // ===== DESCRIPTION // The session_unset() function frees all session variables currently registered. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_unset(): bool // ===== CODE $return_session_unset = session_unset( // 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. // // Notes // Note: If $_SESSION is used, use unset() to unregister a session variable, i.e. unset($_SESSION['varname']);. // Caution: Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal. // Note: The use of session_unset() is identical to $_SESSION = []. // Caution: This function works only if a session is active. It will not clear the $_SESSION array if the session has not been started yet or has already been destroyed. Use $_SESSION = [] to unset all session variables even if the session is not active. // ===== LITERATURE_SOURCES // * PHP_NET (2023-09-09) // URL: https://www.php.net/manual/en/function.session-unset.php // ========== SESSION_UNSET - END // SYNTAX: // bool session_unset() return $return_session_unset; // bool } // ============================== END // PHP_SESSION_SESSIONS_SESSION_UNSET // ============================== // ============================== BEGIN // PHP_SESSION_SESSIONS_SESSION_WRITE_CLOSE // ============================== PUBLIC // ============================== ABOUT // Write session data and end session. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // session_write_close() - PHP_4 >= PHP_4_0_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_session_sessions_session_write_close() { $return_session_write_close = false; // ========== SESSION_WRITE_CLOSE - BEGIN // ===== ABOUT // Write session data and end session // ===== DESCRIPTION // End the current session and store session data. // Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done. // ===== SUPPORTED // PHP_4 >= PHP_4_0_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // session_write_close(): bool // ===== CODE $return_session_write_close = session_write_close( // 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-09) // URL: https://www.php.net/manual/en/function.session-write-close.php // ========== SESSION_WRITE_CLOSE - END // SYNTAX: // bool session_write_close() return $return_session_write_close; // bool } // ============================== END // PHP_SESSION_SESSIONS_SESSION_WRITE_CLOSE // ============================== // ============================== END // PHP_SESSION_SESSIONS // ============================== ?>