Fr3nch13/CakePHP Utilities

Session
in package

This class is a wrapper for the native PHP session functions. It provides several defaults for the most common session configuration via external handlers and helps with using session in CLI without any warnings.

Sessions can be created from the defaults using Session::create() or you can get an instance of a new session by just instantiating this class and passing the complete options you want to use.

When specific options are omitted, this class will take its defaults from the configuration values from the session.* directives in php.ini. This class will also alter such directives when configuration values are provided.

Table of Contents

Properties

$_engine  : SessionHandlerInterface
The Session handler instance used as an engine for persisting the session data.
$_isCLI  : bool
Whether this session is running under a CLI environment
$_lifetime  : int
The time in seconds the session will be valid for
$_started  : bool
Indicates whether the sessions has already started
$headerSentInfo  : array{filename: string, line: int}|null
Info about where the headers were sent.

Methods

__construct()  : mixed
Constructor.
check()  : bool
Returns true if given variable name is set in session.
clear()  : void
Clears the session.
close()  : true
Write data and close the session
consume()  : mixed|null
Reads and deletes a variable from session.
create()  : static
Returns a new instance of a session after building a configuration bundle for it.
delete()  : void
Removes a variable from session.
destroy()  : void
Helper method to destroy invalid sessions.
engine()  : SessionHandlerInterface|null
Sets the session handler instance to use for this session.
id()  : string
Returns the session id.
options()  : void
Calls ini_set for each of the keys in `$options` and set them to the respective value in the passed array.
read()  : mixed|null
Returns given session variable, or all of them, if no parameters given.
readOrFail()  : mixed|null
Returns given session variable, or throws Exception if not found.
renew()  : void
Restarts this session.
start()  : bool
Starts the Session.
started()  : bool
Determine if Session has already been started.
write()  : void
Writes value to given session variable name.
_defaultConfig()  : array<string|int, mixed>|false
Get one of the prebaked default session configurations.
_hasSession()  : bool
Returns whether a session exists
_overwrite()  : void
Used to write new data to _SESSION, since PHP doesn't like us setting the _SESSION var itself.
_timedOut()  : bool
Returns true if the session is no longer valid because the last time it was accessed was after the configured timeout.
setEngine()  : SessionHandlerInterface
Set the engine property and update the session handler in PHP.

Properties

$_engine

The Session handler instance used as an engine for persisting the session data.

protected SessionHandlerInterface $_engine

$_isCLI

Whether this session is running under a CLI environment

protected bool $_isCLI = false

$_lifetime

The time in seconds the session will be valid for

protected int $_lifetime

$_started

Indicates whether the sessions has already started

protected bool $_started

$headerSentInfo

Info about where the headers were sent.

protected array{filename: string, line: int}|null $headerSentInfo = null

Methods

__construct()

Constructor.

public __construct([array<string, mixed> $config = [] ]) : mixed

Configuration:

  • timeout: The time in minutes the session should be valid for.
  • cookiePath: The url path for which session cookie is set. Maps to the session.cookie_path php.ini config. Defaults to base path of app.
  • ini: A list of php.ini directives to change before the session start.
  • handler: An array containing at least the engine key. To be used as the session engine for persisting data. The rest of the keys in the array will be passed as the configuration array for the engine. You can set the engine key to an already instantiated session handler object.
Parameters
$config : array<string, mixed> = []

The Configuration to apply to this session object

check()

Returns true if given variable name is set in session.

public check([string|null $name = null ]) : bool
Parameters
$name : string|null = null

Variable name to check for

Return values
bool

True if variable is there

clear()

Clears the session.

public clear([bool $renew = false ]) : void

Optionally it also clears the session id and renews the session.

Parameters
$renew : bool = false

If session should be renewed, as well. Defaults to false.

close()

Write data and close the session

public close() : true
Return values
true

consume()

Reads and deletes a variable from session.

public consume(string $name) : mixed|null
Parameters
$name : string

The key to read and remove (or a path as sent to Hash.extract).

Return values
mixed|null

The value of the session variable, null if session not available, session not started, or provided name not found in the session.

create()

Returns a new instance of a session after building a configuration bundle for it.

public static create([array<string|int, mixed> $sessionConfig = [] ]) : static

This function allows an options array which will be used for configuring the session and the handler to be used. The most important key in the configuration array is defaults, which indicates the set of configurations to inherit from, the possible defaults are:

  • php: just use session as configured in php.ini
  • cache: Use the CakePHP caching system as an storage for the session, you will need to pass the config key with the name of an already configured Cache engine.
  • database: Use the CakePHP ORM to persist and manage sessions. By default this requires a table in your database named sessions or a model key in the configuration to indicate which Table object to use.
  • cake: Use files for storing the sessions, but let CakePHP manage them and decide where to store them.

The full list of options follows:

  • defaults: either 'php', 'database', 'cache' or 'cake' as explained above.
  • handler: An array containing the handler configuration
  • ini: A list of php.ini directives to set before the session starts.
  • timeout: The time in minutes the session should stay active
Parameters
$sessionConfig : array<string|int, mixed> = []

Session config.

Tags
see
Session::__construct()
Return values
static

delete()

Removes a variable from session.

public delete(string $name) : void
Parameters
$name : string

Session variable to remove

destroy()

Helper method to destroy invalid sessions.

public destroy() : void

engine()

Sets the session handler instance to use for this session.

public engine([SessionHandlerInterface|string|null $class = null ][, array<string, mixed> $options = [] ]) : SessionHandlerInterface|null

If a string is passed for the first argument, it will be treated as the class name and the second argument will be passed as the first argument in the constructor.

If an instance of a SessionHandlerInterface is provided as the first argument, the handler will be set to it.

If no arguments are passed it will return the currently configured handler instance or null if none exists.

Parameters
$class : SessionHandlerInterface|string|null = null

The session handler to use

$options : array<string, mixed> = []

the options to pass to the SessionHandler constructor

Tags
throws
InvalidArgumentException
Return values
SessionHandlerInterface|null

id()

Returns the session id.

public id([string|null $id = null ]) : string

Calling this method will not auto start the session. You might have to manually assert a started session.

Passing an id into it, you can also replace the session id if the session has not already been started. Note that 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).

Parameters
$id : string|null = null

Id to replace the current session id

Return values
string

Session id

options()

Calls ini_set for each of the keys in `$options` and set them to the respective value in the passed array.

public options(array<string, mixed> $options) : void

Example:

$session->options(['session.use_cookies' => 1]);
Parameters
$options : array<string, mixed>

Ini options to set.

Tags
throws
RuntimeException

if any directive could not be set

read()

Returns given session variable, or all of them, if no parameters given.

public read([string|null $name = null ][, mixed $default = null ]) : mixed|null
Parameters
$name : string|null = null

The name of the session variable (or a path as sent to Hash.extract)

$default : mixed = null

The return value when the path does not exist

Return values
mixed|null

The value of the session variable, or default value if a session is not available, can't be started, or provided $name is not found in the session.

readOrFail()

Returns given session variable, or throws Exception if not found.

public readOrFail(string $name) : mixed|null
Parameters
$name : string

The name of the session variable (or a path as sent to Hash.extract)

Tags
throws
RuntimeException
Return values
mixed|null

renew()

Restarts this session.

public renew() : void

start()

Starts the Session.

public start() : bool
Tags
throws
RuntimeException

if the session was already started

Return values
bool

True if session was started

started()

Determine if Session has already been started.

public started() : bool
Return values
bool

True if session has been started.

write()

Writes value to given session variable name.

public write(array<string|int, mixed>|string $name[, mixed $value = null ]) : void
Parameters
$name : array<string|int, mixed>|string

Name of variable

$value : mixed = null

Value to write

_defaultConfig()

Get one of the prebaked default session configurations.

protected static _defaultConfig(string $name) : array<string|int, mixed>|false
Parameters
$name : string

Config name.

Return values
array<string|int, mixed>|false

_hasSession()

Returns whether a session exists

protected _hasSession() : bool
Return values
bool

_overwrite()

Used to write new data to _SESSION, since PHP doesn't like us setting the _SESSION var itself.

protected _overwrite(array<string|int, mixed> &$old, array<string|int, mixed> $new) : void
Parameters
$old : array<string|int, mixed>

Set of old variables => values

$new : array<string|int, mixed>

New set of variable => value

_timedOut()

Returns true if the session is no longer valid because the last time it was accessed was after the configured timeout.

protected _timedOut() : bool
Return values
bool

setEngine()

Set the engine property and update the session handler in PHP.

protected setEngine(SessionHandlerInterface $handler) : SessionHandlerInterface
Parameters
$handler : SessionHandlerInterface

The handler to set

Return values
SessionHandlerInterface

        
On this page

Search results