PHP sessions
Introduction
The HTTP protocol is stateless by itself.
Sessions store user information. They use cookies and do roughly the same as
cookies
but without most of their
drawbacks
Sessions are a tool for managing application state.
Like $_COOKIE, $_SESSION is a superglobal variable
(
array
)
, stored on the web server.
Every session has a unique number, Session ID or SID
A session must be started before sending data to the browser.
Server data and browser cookies work together. The SID is stored in a cookie.
The server «remembers» the user while the site is used within a session.
A session is deleted automatically when the browser closes.
we look at these tasks in the next paragraph
What you can do with sessions
- Store user data on the server. It is safer than cookies. Data is stored in files or in a database
- Frequently used data can be kept in a session. Then accessing it is faster than hitting the database.
- Store unlimited amounts of information. No 4KB limit like cookies have.
- Sessions do not send the same information round and round like cookies - smaller request size.
Example
From everyday life: when you get an electricity bill, it contains lots of different information. But to pay it you only need the account number. Enter the account number and everything else is pulled from the server.
Example client request
Request 1 GET /homepage.php HTTP/1.1 Host: eth1.ru Accept: */*
It is recommended to send the Session ID from the server as a cookie. Another option: pass the Session ID in a URL parameter.
Response 1 HTTP/1.1 200 OK Content-type: text/html Set-Cookie: SID
A request to another page already carries the SID
Request 2 GET /aboutus.php HTTP/1.1 Host: eth1.ru Cookie: SID Accept: */*
Roughly speaking, this is how cookies remember user settings
Where to configure sessions
There are 40+ settings, and several ways to set them.
The first place to set session options is the file
php.ini
.
With the help of
php.ini
can change the settings for the whole PHP server.
In Apache you can use the file
httpd.conf
for the whole server and
.htaccess
for individual directories.
You may already have used .htaccess for redirecting requests
The next way to set options is the ini_set() function. It has to be called with every script that uses sessions, so the method is not very efficient.
Session Configurations Options
The full list is available at http://php.net
session.auto_start: automatically starts a session.
Off by default.
session.name: sets the name of the current session and session cookie
Default is PHPSESSID.
Can be changed with the function
session_name()
session.save_path: the path where session information is stored
Default is the server tmp directory.
session.gc_maxlifetime: maximum lifetime
Default is 1440 seconds (24 minutes).
session.cookie_lifetime: the lifetime of the cookie sent to the browser. Essentially the value we add to time() when
we set
expires
Default is 0.
session.cookie_path: sets
cookie path
Default is '/'.
session.cookie_secure: sets
secure
If enabled, cookies are sent over HTTPS only.
Off by default.
session.use_strict_mode:
if enabled, SIDs not created by the server are rejected.
Off by default.
session.cookie_httponly: sets
httponly
If enabled, the cookie is available over HTTP (and HTTPS) only. That is,
JavaScript
or
bbscripts cannot access the cookie
Off by default.
session.use_cookies: specifies whether to store the SID in
cookies
on the client side.
Enabled by default.
session.use_only_cookies: forces the session to use
only
cookie
for storing the SID. Works together with session.use_cookies
Enabled by default.
session.use_trans_sid: controls the use of «transparent»
SID
If enabled - the SID is appended as a parameter right in the URL. For example:
https://www.eth1.ru/?SID
This option is usually enabled only when there is no support for cookies
Off by default.
Use trans sid with caution as it can compromise user security.
- A user may send a URL containing an active SID to another person by email, irc, etc.
- A URL containing an active SID may get saved on a publicly accessible computer.
- - A user may visit your site with the same SID saved in bookmarks or browser history.
Details at http://php.net/session.use-trans-sid
session.cache_limiter: specifies how caching is controlled during a session.
Available options:
- nocache
- private
- private_no_expire
- public
Default nocache.
For sessions with authentication browser caching must be disabled.
Read more:
http://php.net
http://php.net
session.cookie_samesite: controls cookie availability in cross-domain requests.
Available options: Lax and Strict
Cross-domain requests do not only come from attackers. Your site may make them from different subdomains. Or you may track user movement between your projects.
Functions
The full list is available at php.net
session_start(): starts a session and makes the variable available $_SESSION.
session_name(): renames the session.
Changes the value set with the function
session.name.
session_id(): gets or sets the current session id
set new session ID: session_id('<new SID>')
session_destroy(): deletes all information recorded in the session
Example .htaccess
Your server settings may differ, this is just an example
# Use php_flag for boolean values, # php_flag session.auto_start off php_flag session.use_cookies on php_flag session.use_only_cookies on php_flag session.use_trans_sid off php_flag session.use_strict_mode on # Use php_value for non-boolean values # Enclose values that contain punctuation in quotes. php_value session.cache_limiter nocache php_value session.cookie_samesite Lax php_value session.name AOSESSID php_value session.save_path ./tmp # Cookie settings php_value session.cookie_path '/' php_value session.cookie_lifetime 0 php_flag session.cookie_httponly on php_flag session.cookie_secure on
Session initialization
A session starts with the function
session_start()
This function must be included in every script where you need sessions.
First it checks for an active session. If there is none - it starts a new one.
Saves data in a super global variable
$_SESSION,
which is
an array
session_start();
$_SESSION['username'] = 'Andrei';
echo isset($_SESSION['username']) ? $_SESSION['username'] : 'Not available';
If the last line is unclear to you - read the article
«Ternary operator in PHP»
You can demo session_start() in your browser on
this page
You can view cookies in Chrome DevTools → Application → Cookies
Select aredel.com or eth1.ru and find AOSESSID
You can inspect the file with session data in the directory you specified in
php_value session.save_path
In mine .htaccess specified
php_value session.save_path ./tmp
That is why I look at the contents there
cat ./tmp/sess_d510566d6fc7dcbf9a9c21eb29d846ce
username|s:6:"Andrei";
Deleting a session
A session expires when the browser closes, on timeout, or when explicitly expired.
If you do not delete the data, it stays on the server - which is unsafe.
Destroying a session includes:
- Deleting all variables in the session
- Deleting data on the server
- Deleting cookies on the client
session_destroy()
Deletes all data bound to the session.
Does not delete any variables from the superglobal variable
$_SESSION.
Does not delete cookies.
Returns boolean - whether the data was deleted or not
If using only session_destroy() can be reused $_SESSION by simply calling session_start()
unset()
unset() is a standard PHP function, used not only with sessions.
To clear username run
unset($_SESSION['username']);
To clear everything you can do without unset()
$_SESSION = [];
Example of full session deletion
$_SESSION = [];
$params = session_get_cookie_params();
$options = array('lifetime' => time() - 60);
setcookie(session_name(), '', $options);
session_destroy();
Article author: Andrei Olegovich