PHP library for handling sessions.
- Requirements
- Installation
- Available Classes
- Exceptions Used
- Usage
- Security Best Practices
- Tests
- TODO
- Changelog
- Contribution
- Sponsor
- License
-
Operating System: Linux | Windows.
-
PHP: 8.0–8.5.
The preferred way to install this extension is through Composer.
To install PHP Session library, simply:
composer require josantonius/sessionThe previous command will only install the necessary files, if you prefer to download the entire source code you can use:
composer require josantonius/session --prefer-sourceYou can also clone the complete repository with Git:
git clone https://github.com/josantonius/php-session.gitJosantonius\Session\Session
Starts the session:
/**
* @throws HeadersSentException if headers already sent.
* @throws SessionStartedException if session already started.
* @throws WrongSessionOptionException if setting options failed.
*
* @see https://php.net/session.configuration for List of available $options.
*/
public function start(array $options = []): bool;Check if the session is started:
public function isStarted(): bool;Sets an attribute by name:
/**
* @throws SessionNotStartedException if session was not started.
*/
public function set(string $name, mixed $value): void;Gets an attribute by name:
/**
* Optionally defines a default value when the attribute does not exist.
*/
public function get(string $name, mixed $default = null): mixed;Gets all attributes:
public function all(): array;Check if an attribute exists in the session:
public function has(string $name): bool;Sets several attributes at once:
/**
* If attributes exist they are replaced, if they do not exist they are created.
*
* @throws SessionNotStartedException if session was not started.
*/
public function replace(array $data): void;Deletes an attribute by name and returns its value:
/**
* Optionally defines a default value when the attribute does not exist.
*
* @throws SessionNotStartedException if session was not started.
*/
public function pull(string $name, mixed $default = null): mixed;Deletes an attribute by name:
/**
* @throws SessionNotStartedException if session was not started.
*/
public function remove(string $name): void;Free all session variables:
/**
* @throws SessionNotStartedException if session was not started.
*/
public function clear(): void;Gets the session ID:
public function getId(): string;Sets the session ID:
/**
* @throws SessionStartedException if session already started.
*/
public function setId(string $sessionId): void;Update the current session ID with a newly generated one:
/**
* @throws SessionNotStartedException if session was not started.
*/
public function regenerateId(bool $deleteOldSession = false): bool;Gets the session name:
public function getName(): string;Sets the session name:
/**
* @throws SessionStartedException if session already started.
*/
public function setName(string $name): void;Destroys the session:
/**
* @throws SessionNotStartedException if session was not started.
*/
public function destroy(): bool;Josantonius\Session\Facades\Session
Starts the session:
/**
* @throws HeadersSentException if headers already sent.
* @throws SessionStartedException if session already started.
* @throws WrongSessionOptionException if setting options failed.
*
* @see https://php.net/session.configuration for List of available $options.
*/
public static function start(array $options = []): bool;Check if the session is started:
public static function isStarted(): bool;Sets an attribute by name:
/**
* @throws SessionNotStartedException if session was not started.
*/
public static function set(string $name, mixed $value): void;Gets an attribute by name:
/**
* Optionally defines a default value when the attribute does not exist.
*/
public static function get(string $name, mixed $default = null): mixed;Gets all attributes:
public static function all(): array;Check if an attribute exists in the session:
public static function has(string $name): bool;Sets several attributes at once:
/**
* If attributes exist they are replaced, if they do not exist they are created.
*
* @throws SessionNotStartedException if session was not started.
*/
public static function replace(array $data): void;Deletes an attribute by name and returns its value:
/**
* Optionally defines a default value when the attribute does not exist.
*
* @throws SessionNotStartedException if session was not started.
*/
public static function pull(string $name, mixed $default = null): mixed;Deletes an attribute by name:
/**
* @throws SessionNotStartedException if session was not started.
*/
public static function remove(string $name): void;Free all session variables:
/**
* @throws SessionNotStartedException if session was not started.
*/
public static function clear(): void;Gets the session ID:
public static function getId(): string;Sets the session ID:
/**
* @throws SessionStartedException if session already started.
*/
public static function setId(string $sessionId): void;Update the current session ID with a newly generated one:
/**
* @throws SessionNotStartedException if session was not started.
*/
public static function regenerateId(bool $deleteOldSession = false): bool;Gets the session name:
public static function getName(): string;Sets the session name:
/**
* @throws SessionStartedException if session already started.
*/
public static function setName(string $name): void;Destroys the session:
/**
* @throws SessionNotStartedException if session was not started.
*/
public static function destroy(): bool;use Josantonius\Session\Exceptions\HeadersSentException;
use Josantonius\Session\Exceptions\SessionException;
use Josantonius\Session\Exceptions\SessionNotStartedException;
use Josantonius\Session\Exceptions\SessionStartedException;
use Josantonius\Session\Exceptions\WrongSessionOptionException;Example of use for this library:
use Josantonius\Session\Session;
$session = new Session();
$session->start();use Josantonius\Session\Facades\Session;
Session::start();Recommended configuration for an HTTPS application. Adjust it to your application's needs; see Security Best Practices.
use Josantonius\Session\Session;
$session = new Session();
$session->start([
'use_strict_mode' => true,
'use_only_cookies' => true,
'use_cookies' => true,
'cookie_httponly' => true,
'cookie_secure' => true,
'cookie_samesite' => 'Lax',
]);use Josantonius\Session\Facades\Session;
Session::start([
'use_strict_mode' => true,
'use_only_cookies' => true,
'use_cookies' => true,
'cookie_httponly' => true,
'cookie_secure' => true,
'cookie_samesite' => 'Lax',
]);use Josantonius\Session\Session;
$session = new Session();
$session->isStarted();use Josantonius\Session\Facades\Session;
Session::isStarted();use Josantonius\Session\Session;
$session = new Session();
$session->set('foo', 'bar');use Josantonius\Session\Facades\Session;
Session::set('foo', 'bar');use Josantonius\Session\Session;
$session = new Session();
$session->get('foo'); // null if attribute does not existuse Josantonius\Session\Facades\Session;
Session::get('foo'); // null if attribute does not existuse Josantonius\Session\Session;
$session = new Session();
$session->get('foo', false); // false if attribute does not existuse Josantonius\Session\Facades\Session;
Session::get('foo', false); // false if attribute does not existuse Josantonius\Session\Session;
$session = new Session();
$session->all();use Josantonius\Session\Facades\Session;
Session::all();use Josantonius\Session\Session;
$session = new Session();
$session->has('foo');use Josantonius\Session\Facades\Session;
Session::has('foo');use Josantonius\Session\Session;
$session = new Session();
$session->replace(['foo' => 'bar', 'bar' => 'foo']);use Josantonius\Session\Facades\Session;
Session::replace(['foo' => 'bar', 'bar' => 'foo']);use Josantonius\Session\Session;
$session = new Session();
$session->pull('foo'); // null if attribute does not existuse Josantonius\Session\Facades\Session;
Session::pull('foo'); // null if attribute does not existuse Josantonius\Session\Session;
$session = new Session();
$session->pull('foo', false); // false if attribute does not existuse Josantonius\Session\Facades\Session;
Session::pull('foo', false); // false if attribute does not existuse Josantonius\Session\Session;
$session = new Session();
$session->remove('foo');use Josantonius\Session\Facades\Session;
Session::remove('foo');use Josantonius\Session\Session;
$session = new Session();
$session->clear();use Josantonius\Session\Facades\Session;
Session::clear();use Josantonius\Session\Session;
$session = new Session();
$session->getId();use Josantonius\Session\Facades\Session;
Session::getId();use Josantonius\Session\Session;
$session = new Session();
$session->setId('foo');use Josantonius\Session\Facades\Session;
Session::setId('foo');use Josantonius\Session\Session;
$session = new Session();
$session->regenerateId();use Josantonius\Session\Facades\Session;
Session::regenerateId();Immediate deletion can disrupt concurrent requests. Read Security Best Practices before choosing this option.
use Josantonius\Session\Session;
$session = new Session();
$session->regenerateId(true);use Josantonius\Session\Facades\Session;
Session::regenerateId(true);use Josantonius\Session\Session;
$session = new Session();
$session->getName();use Josantonius\Session\Facades\Session;
Session::getName();use Josantonius\Session\Session;
$session = new Session();
$session->setName('foo');use Josantonius\Session\Facades\Session;
Session::setName('foo');use Josantonius\Session\Session;
$session = new Session();
$session->destroy();use Josantonius\Session\Facades\Session;
Session::destroy();The library uses PHP's session configuration, including settings from php.ini, ini_set() and
session_set_cookie_params(). Options passed to Session::start() override those settings; omitted
options keep their current values. Choose settings that suit your environment and application.
- Enable
use_strict_modeto reject uninitialized session IDs. The built-infileshandler supports it. Custom handlers need ID validation throughSessionUpdateTimestampHandlerInterface::validateId()or thevalidate_sidcallback. - Enable
cookie_httponlyto prevent JavaScript from reading the session cookie. - Use HTTPS throughout the authenticated application and enable
cookie_secureso the cookie is sent only over secure connections. Secure cookies generally do not work over plain HTTP. - Keep
use_only_cookiesanduse_cookiesenabled to avoid exposing session IDs in URLs.
See PHP's session security settings.
Choose cookie_samesite according to your application's navigation and authentication flows:
| Value | Behavior and compatibility |
|---|---|
Lax |
Sends cookies on same-site requests and top-level cross-site navigation using safe methods such as GET. Suitable for many applications, but can disrupt cross-site POST callbacks and embedded content. |
Strict |
Sends cookies only on same-site requests. Following a link from another site can initially omit the session cookie. |
None |
Allows cross-site cookies and requires cookie_secure = true in modern browsers. Older clients may interpret it differently, and third-party-cookie restrictions can still block it. |
Keep CSRF protection and XSS prevention in place regardless of cookie settings. Check the browser compatibility details for the clients your application supports.
cookie_partitioned enables cookies partitioned by top-level site (CHIPS), useful for some embedded
services. It requires PHP 8.5+ and cookie_secure = true. Omitting it keeps PHP's configured value.
On older PHP versions, supplying it throws WrongSessionOptionException, even as false.
See the PHP reference.
Call regenerateId() after verifying credentials or authorizing a privilege change, before saving
the new identity or privileges. use_strict_mode does not replace regeneration. start() does not
regenerate IDs automatically.
With an active $session and an $authenticatedUserId obtained by verifying credentials:
if (!$session->regenerateId()) {
throw new RuntimeException('Session ID regeneration failed.');
}
$session->set('user_id', $authenticatedUserId);regenerateId() keeps the old session data; regenerateId(true) deletes it immediately, which can
disrupt concurrent requests or unstable connections. Manage old IDs with timestamps and a short,
bounded transition period. New privileges must belong only to the new ID, and access through the old
ID must expire independently of PHP's garbage collection. See PHP's
session management guidance
and regeneration examples.
PHP defaults can change between releases. The accepted
PHP 8.6 RFC enables use_strict_mode and
cookie_httponly by default and sets cookie_samesite to Lax. Existing configuration can override
these values. Set the options your application needs explicitly, especially for custom session IDs
or cross-site authentication. See Requirements for compatible PHP versions.
To report a vulnerability privately, see SECURITY.md.
To run tests you just need composer and to execute the following:
git clone https://github.com/josantonius/php-session.gitcd php-sessioncomposer installRun unit tests with PHPUnit:
composer phpunitRun code standard tests with PHPCS:
composer phpcsRun PHP Mess Detector tests to detect inconsistencies in code style:
composer phpmdRun all previous tests:
composer tests- Add new feature
- Improve tests
- Improve documentation
- Refactor code for disabled code style rules (see phpmd.xml and phpcs.xml)
- Show an example of renewing the session lifetime
- Feature to enable/disable exceptions?
- Feature to add prefixes in session attributes?
Detailed changes for each release are documented in the release notes.
Please make sure to read the Contributing Guide, before making a pull request, start a discussion or report a issue.
Thanks to all contributors! ❤️
If this project helps you to reduce your development time, you can sponsor me to support my open source work 😊
This repository is licensed under the MIT License.
Copyright © 2017-present, Josantonius