This post covers the Sessions section of the Web Features chapter when studying for the Zend PHP 7 Certification.
Sessions are a way of preserving information across a series of website accesses by the user.
A visitor accessing your web site is assigned a unique ID, the session ID. This is either stored in a cookie on the user side or is propagated in the URL.
By default, sessions support is enabled.
When a visitor accesses your site, PHP will check automatically (if the
session.auto_start configuration directive 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.
For a session to store information in a cookie, the following must be set in the
php.ini configuration file
session.use_cookies = 1
Additionally, you can also use the below directive.
session.use_only_cookies = 1
In PHP session data is usually stored in a file. The only thing stored in the cookie is a session identifier. When sessions are enabled and a valid session cookie is found, PHP loads the users session data from the file into a super global called funnily enough
$_SESSION a global variable.
Basic sessions are started using
session_start() where the user is assigned a unique identifier.
The location of the
$_SESSION variable storage is determined by PHP’s
session.save_path configuration. The storage is usually saved in a
/tmp folder however this can be changed by altering the directive in
The session lifetime is determined by the value specified in the server configuration or the relevant directives (
php.ini. Typically the default is 24 minutes (1440 seconds).
The session cookie lifetime directive is
php.ini and its value is usually set to 0 so that the session cookie is valid until the browser is closed.
session_regenerate_id() function will replace the current session ID with a new one, and keep the current session information. This can used when the user is editing or updating some important inputs (changing passwords, credentials, forgot passwords etc.) which may compromise security. This function will help prevent session fixation attacks.
Note that by passing in
true as a parameter in the
session_regenerate_id() function like the below.
This will delete the old associated session file.
To destroy sessions, use the PHP function
Note: This article is based on PHP version 7.1.