PHP sessions

Contents
Introduction
What sessions are for
Where to configure sessions
session.configuration: options
Functions
.htaccess example
session_start(): starting a session
ending a session
working with variables
Preserving data
Storing sessions in MySQL

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

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.

Details at http://php.net/session.use-trans-sid

session.cache_limiter: specifies how caching is controlled during a session.

Available options:

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:

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

Related articles
Development with PHP
Arrays in PHP
Date and Time in PHP - basics
How to display time of multiple timezones in PHP
How to add variable to url in PHP
json_decode
How to get screen size with PHP
Call function from another file
Premature end of chunk coded message body: closing chunk expected
Generate unique random numbers with PHP
Check your HTTP_USER_AGENT
Compare two dates
OOP
Namespaces in PHP
Comments in PHP
Cookies
PHP sessions
Authentication and Authorization in PHP 8
PHP linters we use
PHP errors: case studies
card_from_db(): banner card from a DB row
PHP versions: history in brief
Creating rules in .htaccess
require, require_once, include, include_once
Flat pair arrays: three pitfalls from the Related articles block
Deduplication in PHP
PHP course: zero to hero in 50 lessons

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: