Skip to content
PHP Ecosystem
Explore

Session

API reference › yii › web › Session

3 subclasses

Session provides session data management and the related configurations.

Session is a Web application component that can be accessed via Yii::$app->session.

To start the session, call open(); To complete and send out session data, call close(); To destroy the session, call destroy().

Session can be used like an array to set and get session data. For example,

$session = new Session;
$session->open();
$value1 = $session['name1']; // get session variable 'name1'
$value2 = $session['name2']; // get session variable 'name2'
foreach ($session as $name => $value) // traverse all session variables
$session['name3'] = $value3; // set session variable 'name3'

Session can be extended to support customized session storage. To do so, override $useCustomStorage so that it returns true, and override these methods with the actual logic about using custom storage: openSession(), closeSession(), readSession(), writeSession(), destroySession() and gcSession().

Session also supports a special type of session data, called flash messages. A flash message is available only in the current request and the next request. After that, it will be deleted automatically. Flash messages are particularly useful for displaying confirmation messages. To use flash messages, simply call methods such as setFlash(), getFlash().

For more details and usage information on Session, see the guide article on sessions.

PropertyTypeDescriptionDefined by
$allFlashes read-onlyarrayFlash messages (key => message or key => [message1, message2]).Session
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$cacheLimiterstringCurrent cache limiter.Session
$cookieParamsarrayThe session cookie parameters.Session
$count read-onlyintThe number of session variables.Session
$flash write-onlystringThe key identifying the flash message.Session
$flashParamstringThe name of the session variable that stores the flash message data. Default: '__flash'.Session
$gCProbabilityfloatThe probability (percentage) that the GC (garbage collection) process is started on every session initialization.Session
$handlerSessionHandlerInterface|arrayAn object implementing the SessionHandlerInterface or a configuration array. Default: null.Session
$hasSessionIdboolWhether the current request has sent the session ID.Session
$idstringThe current session ID.Session
$isActive read-onlyboolWhether the session has started.Session
$iterator read-onlySessionIteratorAn iterator for traversing the session variables.Session
$namestringThe current session name.Session
$savePathstringThe current session save path, defaults to ‘/tmp’.Session
$timeoutintThe number of seconds after which data will be seen as ‘garbage’ and cleaned up.Session
$useCookiesbool|nullThe value indicating whether cookies should be used to store session IDs.Session
$useCustomStorage read-onlyboolWhether to use custom storage.Session
$useStrictModeboolWhether strict mode is enabled or not.Session
$useTransparentSessionIDboolWhether transparent sid support is enabled or not, defaults to false.Session
$_forceRegenerateId protectedstring|nullHolds the session id in case useStrictMode is enabled and the session id needs to be regenerated Default: null.Session
$_originalSessionModule protected staticstring|nullHolds the original session module (before a custom handler is registered) so that it can be restored when a Session component without custom handler is used after one that has. Default: null.Session
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\Component
__clone()This method is called after the object is created by cloning an existing one.yii\base\Component
__get()Returns the value of a component property.yii\base\Component
__isset()Checks if a property is set, i.e. defined and not null.yii\base\Component
__set()Sets the value of a component property.yii\base\Component
__unset()Sets a component property to be null.yii\base\Component
addFlash()Adds a flash message.Session
attachBehavior()Attaches a behavior to this component.yii\base\Component
attachBehaviors()Attaches a list of behaviors to the component.yii\base\Component
behaviors()Returns a list of behaviors that this component should behave as.yii\base\Component
canGetProperty()Returns a value indicating whether a property can be read.yii\base\Component
canSetProperty()Returns a value indicating whether a property can be set.yii\base\Component
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
close()Ends the current session and store session data.Session
count()Returns the number of items in the session.Session
destroy()Frees all session variables and destroys all data registered to a session.Session
detachBehavior()Detaches a behavior from the component.yii\base\Component
detachBehaviors()Detaches all behaviors from the component.yii\base\Component
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.yii\base\Component
get()Returns the session variable value with the session variable name.Session
getAllFlashes()Returns all flash messages.Session
getBehavior()Returns the named behavior object.yii\base\Component
getBehaviors()Returns all behaviors attached to this component.yii\base\Component
getCacheLimiter()Returns current cache limiterSession
getCookieParams()Session
getCount()Returns the number of items in the session.Session
getFlash()Returns a flash message.Session
getGCProbability()Session
getHasSessionId()Returns a value indicating whether the current request has sent the session ID.Session
getId()Gets the session ID.Session
getIsActive()Session
getIterator()Returns an iterator for traversing the session variables.Session
getName()Gets the name of the current session.Session
getSavePath()Gets the current session save path.Session
getTimeout()Session
getUseCookies()Returns the value indicating whether cookies should be used to store session IDs.Session
getUseCustomStorage()Returns a value indicating whether to use custom session storage.Session
getUseStrictMode()Session
getUseTransparentSessionID()Session
has()Session
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.yii\base\Component
hasFlash()Returns a value indicating whether there are flash messages associated with the specified key.Session
hasMethod()Returns a value indicating whether a method is defined.yii\base\Component
hasProperty()Returns a value indicating whether a property is defined for this component.yii\base\Component
init()Initializes the application component.Session
off()Detaches an existing event handler from this component.yii\base\Component
offsetExists()This method is required by the interface ArrayAccess.Session
offsetGet()This method is required by the interface ArrayAccess.Session
offsetSet()This method is required by the interface ArrayAccess.Session
offsetUnset()This method is required by the interface ArrayAccess.Session
on()Attaches an event handler to an event.yii\base\Component
open()Starts the session.Session
regenerateID()Updates the current session ID with a newly generated one.Session
remove()Removes a session variable.Session
removeAll()Removes all session variables.Session
removeAllFlashes()Removes all flash messages.Session
removeFlash()Removes a flash message.Session
set()Adds a session variable.Session
setCacheLimiter()Set cache limiterSession
setCookieParams()Sets the session cookie parameters.Session
setFlash()Sets a flash message.Session
setGCProbability()Session
setHasSessionId()Sets the value indicating whether the current request has sent the session ID.Session
setId()Sets the session ID.Session
setName()Sets the name for the current session.Session
setSavePath()Sets the current session save path.Session
setTimeout()Session
setUseCookies()Sets the value indicating whether cookies should be used to store session IDs.Session
setUseStrictMode()Session
setUseTransparentSessionID()Session
trigger()Triggers an event.yii\base\Component
freeze() protectedIf session is started it’s not possible to edit session ini settings. In PHP7.2+ it throws exception.Session
registerSessionHandler() protectedRegisters session handler.Session
unfreeze() protectedStarts session and restores data from temporary variableSession
updateFlashCounters() protectedUpdates the counters for flash messages and removes outdated flash messages.Session
public string $flash

The key identifying the flash message.

Note that flash messages and normal session variables share the same name space. If you have a normal session variable using the same name, its value will be overwritten by this method.

Access

Write-only (virtual property).

public SessionHandlerInterface|array $handler = null

An object implementing the SessionHandlerInterface or a configuration array.

If set, will be used to provide persistency instead of build-in methods.

public int $timeout

The number of seconds after which data will be seen as ‘garbage’ and cleaned up.

The default value is 1440 seconds (or the value of “session.gc_maxlifetime” set in php.ini).

public function addFlash(string $key, mixed $value = true, bool $removeAfterAccess = true): mixed

Adds a flash message.

If there are existing flash messages with the same key, the new one will be appended to the existing message array.

Parameters

ParameterTypeDescription
$keystringThe key identifying the flash message.
$valuemixedFlash message
$removeAfterAccessboolWhether the flash message should be automatically removed only if it is accessed. If false, the flash message will be automatically removed after the next request, regardless if it is accessed or not. If true (default value), the flash message will remain until after it is accessed.

Returns

mixed

See also

public function close(): mixed

Ends the current session and store session data.

Returns

mixed

public function count(): int

Returns the number of items in the session.

This method is required by Countable interface.

Returns

int: Number of items in the session.

public function destroy(): mixed

Frees all session variables and destroys all data registered to a session.

This method has no effect when session is not active. Make sure to call open() before calling it.

Returns

mixed

See also

public function get(string $key, mixed $defaultValue = null): mixed

Returns the session variable value with the session variable name.

If the session variable does not exist, the $defaultValue will be returned.

Parameters

ParameterTypeDescription
$keystringThe session variable name
$defaultValuemixedThe default value to be returned when the session variable does not exist.

Returns

mixed: The session variable value, or $defaultValue if the session variable does not exist.

public function getAllFlashes(bool $delete = false): array

Returns all flash messages.

You may use this method to display all the flash messages in a view file:

<?php
foreach (Yii::$app->session->getAllFlashes() as $key => $message) {
echo \yii\helpers\Html::tag(
'div',
\yii\helpers\Html::encode($message),
[
'class' => 'flash-' . \yii\helpers\Html::encode($key),
],
);
} ?>

With the above code you can use the flash message key (for example success, info, danger) to style the container with your own CSS framework. Both $key and $message are HTML-encoded to prevent cross-site scripting when flash content comes from untrusted input.

Note that if you use addFlash(), $message will be an array, and you will have to adjust the above code to iterate over each entry and encode it individually.

Parameters

ParameterTypeDescription
$deleteboolWhether to delete the flash messages right after this method is called. If false, the flash messages will be automatically deleted in the next request.

Returns

array: Flash messages (key => message or key => [message1, message2]).

See also

public function getCacheLimiter(): string

Returns current cache limiter

Returns

string: Current cache limiter

Since

2.0.14

public function getCookieParams(): array

Returns

array: The session cookie parameters.

See also

public function getCount(): int

Returns the number of items in the session.

Returns

int: The number of session variables

public function getFlash(string $key, mixed $defaultValue = null, bool $delete = false): mixed

Returns a flash message.

Parameters

ParameterTypeDescription
$keystringThe key identifying the flash message
$defaultValuemixedValue to be returned if the flash message does not exist.
$deleteboolWhether to delete this flash message right after this method is called. If false, the flash message will be automatically deleted in the next request.

Returns

mixed: The flash message or an array of messages if addFlash was used

See also

public function getGCProbability(): float

Returns

float: The probability (percentage) that the GC (garbage collection) process is started on every session initialization.

public function getHasSessionId(): bool

Returns a value indicating whether the current request has sent the session ID.

The default implementation will check cookie and $_GET using the session name. If you send session ID via other ways, you may need to override this method or call setHasSessionId() to explicitly set whether the session ID is sent.

Returns

bool: Whether the current request has sent the session ID.

public function getId(): string

Gets the session ID.

This is a wrapper for PHP session_id().

Returns

string: The current session ID

public function getIsActive(): bool

Returns

bool: Whether the session has started

public function getIterator(): yii\web\SessionIterator

Returns an iterator for traversing the session variables.

This method is required by the interface IteratorAggregate.

Returns

SessionIterator: An iterator for traversing the session variables.

public function getName(): string

Gets the name of the current session.

This is a wrapper for PHP session_name().

Returns

string: The current session name

public function getSavePath(): string

Gets the current session save path.

This is a wrapper for PHP session_save_path().

Returns

string: The current session save path, defaults to ‘/tmp’.

public function getTimeout(): int

Returns

int: The number of seconds after which data will be seen as ‘garbage’ and cleaned up. The default value is 1440 seconds (or the value of “session.gc_maxlifetime” set in php.ini).

public function getUseCookies(): bool|null

Returns the value indicating whether cookies should be used to store session IDs.

Returns

bool|null: The value indicating whether cookies should be used to store session IDs.

See also

public function getUseCustomStorage(): bool

Returns a value indicating whether to use custom session storage.

This method should be overridden to return true by child classes that implement custom session storage. To implement custom session storage, override these methods: openSession(), closeSession(), readSession(), writeSession(), destroySession() and gcSession().

Returns

bool: Whether to use custom storage.

public function getUseStrictMode(): bool

Returns

bool: Whether strict mode is enabled or not.

Since

2.0.38

See also

public function getUseTransparentSessionID(): bool

Returns

bool: Whether transparent sid support is enabled or not, defaults to false.

public function has(mixed $key): bool

Parameters

ParameterTypeDescription
$keymixedSession variable name

Returns

bool: Whether there is the named session variable

public function hasFlash(string $key): bool

Returns a value indicating whether there are flash messages associated with the specified key.

Parameters

ParameterTypeDescription
$keystringKey identifying the flash message type

Returns

bool: Whether any flash messages exist under specified key

public function init(): mixed

Initializes the application component.

This method is required by IApplicationComponent and is invoked by application.

Returns

mixed

public function offsetExists(int|string $offset): bool

This method is required by the interface ArrayAccess.

Parameters

ParameterTypeDescription
$offsetint|stringThe offset to check on

Returns

bool

public function offsetGet(int|string $offset): mixed

This method is required by the interface ArrayAccess.

Parameters

ParameterTypeDescription
$offsetint|stringThe offset to retrieve element.

Returns

mixed: The element at the offset, null if no element is found at the offset

public function offsetSet(int|string $offset, mixed $item): mixed

This method is required by the interface ArrayAccess.

Parameters

ParameterTypeDescription
$offsetint|stringThe offset to set element
$itemmixedThe element value

Returns

mixed

public function offsetUnset(int|string $offset): mixed

This method is required by the interface ArrayAccess.

Parameters

ParameterTypeDescription
$offsetint|stringThe offset to unset element

Returns

mixed

public function open(): mixed

Starts the session.

Returns

mixed

public function regenerateID(bool $deleteOldSession = false): mixed

Updates the current session ID with a newly generated one.

Please refer to https://www.php.net/session_regenerate_id for more details.

This method has no effect when session is not active. Make sure to call open() before calling it.

Parameters

ParameterTypeDescription
$deleteOldSessionboolWhether to delete the old associated session file or not.

Returns

mixed

See also

public function remove(string $key): mixed

Removes a session variable.

Parameters

ParameterTypeDescription
$keystringThe name of the session variable to be removed

Returns

mixed: The removed value, null if no such session variable.

public function removeAll(): mixed

Removes all session variables.

Returns

mixed

public function removeAllFlashes(): mixed

Removes all flash messages.

Note that flash messages and normal session variables share the same name space. If you have a normal session variable using the same name, it will be removed by this method.

public function removeFlash(string $key): mixed

Removes a flash message.

Parameters

ParameterTypeDescription
$keystringThe key identifying the flash message. Note that flash messages and normal session variables share the same name space. If you have a normal session variable using the same name, it will be removed by this method.

Returns

mixed: The removed flash message. Null if the flash message does not exist.

See also

public function set(string $key, mixed $value): mixed

Adds a session variable.

If the specified name already exists, the old value will be overwritten.

Parameters

ParameterTypeDescription
$keystringSession variable name
$valuemixedSession variable value

Returns

mixed

public function setCacheLimiter(string $cacheLimiter): mixed

Set cache limiter

Parameters

ParameterTypeDescription
$cacheLimiterstring

Returns

mixed

Since

2.0.14

public function setCookieParams(array $value): mixed

Sets the session cookie parameters.

The cookie parameters passed to this method will be merged with the result of session_get_cookie_params().

Parameters

ParameterTypeDescription
$valuearrayCookie parameters, valid keys include: lifetime, path, domain, secure, httponly and sameSite. [ ‘sameSite’ => yii\web\Cookie::SAME_SITE_LAX, ] See https://owasp.org/www-community/SameSite for more information about sameSite.

Returns

mixed

Throws

See also

public function setFlash(string $key, mixed $value = true, bool $removeAfterAccess = true): mixed

Sets a flash message.

A flash message will be automatically deleted after it is accessed in a request and the deletion will happen in the next request. If there is already an existing flash message with the same key, it will be overwritten by the new one.

Parameters

ParameterTypeDescription
$keystringThe key identifying the flash message. Note that flash messages and normal session variables share the same name space. If you have a normal session variable using the same name, its value will be overwritten by this method.
$valuemixedFlash message
$removeAfterAccessboolWhether the flash message should be automatically removed only if it is accessed. If false, the flash message will be automatically removed after the next request, regardless if it is accessed or not. If true (default value), the flash message will remain until after it is accessed.

Returns

mixed

See also

public function setGCProbability(float $value): mixed

Parameters

ParameterTypeDescription
$valuefloatThe probability (percentage) that the GC (garbage collection) process is started on every session initialization.

Returns

mixed

Throws

public function setHasSessionId(bool $value): mixed

Sets the value indicating whether the current request has sent the session ID.

This method is provided so that you can override the default way of determining whether the session ID is sent.

Parameters

ParameterTypeDescription
$valueboolWhether the current request has sent the session ID.

Returns

mixed

public function setId(string $value): mixed

Sets the session ID.

This is a wrapper for PHP session_id().

Parameters

ParameterTypeDescription
$valuestringThe session ID for the current session

Returns

mixed

public function setName(string $value): mixed

Sets the name for the current session.

This is a wrapper for PHP session_name().

Parameters

ParameterTypeDescription
$valuestringThe session name for the current session, must be an alphanumeric string. It defaults to “PHPSESSID”.

Returns

mixed

public function setSavePath(string $value): mixed

Sets the current session save path.

This is a wrapper for PHP session_save_path().

Parameters

ParameterTypeDescription
$valuestringThe current session save path. This can be either a directory name or a path alias.

Returns

mixed

Throws

public function setTimeout(int $value): mixed

Parameters

ParameterTypeDescription
$valueintThe number of seconds after which data will be seen as ‘garbage’ and cleaned up

Returns

mixed

public function setUseCookies(bool|null $value): mixed

Sets the value indicating whether cookies should be used to store session IDs.

Three states are possible:

  • true: cookies and only cookies will be used to store session IDs.
  • false: cookies will not be used to store session IDs.
  • null: if possible, cookies will be used to store session IDs; if not, other mechanisms will be used (e.g. GET parameter)

Parameters

ParameterTypeDescription
$valuebool|nullThe value indicating whether cookies should be used to store session IDs.

Returns

mixed

public function setUseStrictMode(bool $value): mixed

Parameters

ParameterTypeDescription
$valueboolWhether strict mode is enabled or not. When true this setting prevents the session component to use an uninitialized session ID. Note: Enabling useStrictMode on PHP < 5.5.2 is only supported with custom storage classes. Warning! Although enabling strict mode is mandatory for secure sessions, the default value of ‘session.use-strict-mode’ is 0.

Returns

mixed

Since

2.0.38

See also

public function setUseTransparentSessionID(bool $value): mixed

Parameters

ParameterTypeDescription
$valueboolWhether transparent sid support is enabled or not.

Returns

mixed

protected function freeze(): mixed

If session is started it’s not possible to edit session ini settings. In PHP7.2+ it throws exception.

This function saves session data to temporary variable and stop session.

Returns

mixed

Since

2.0.14

protected function registerSessionHandler(): mixed

Registers session handler.

Returns

mixed

Throws

protected function unfreeze(): mixed

Starts session and restores data from temporary variable

Returns

mixed

Since

2.0.14

protected function updateFlashCounters(): mixed

Updates the counters for flash messages and removes outdated flash messages.

This method should only be called once in init().

Returns

mixed