Session
API reference › yii › web › Session
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.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$allFlashes read-only | array | Flash messages (key => message or key => [message1, message2]). | Session |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$cacheLimiter | string | Current cache limiter. | Session |
$cookieParams | array | The session cookie parameters. | Session |
$count read-only | int | The number of session variables. | Session |
$flash write-only | string | The key identifying the flash message. | Session |
$flashParam | string | The name of the session variable that stores the flash message data. Default: '__flash'. | Session |
$gCProbability | float | The probability (percentage) that the GC (garbage collection) process is started on every session initialization. | Session |
$handler | SessionHandlerInterface| | An object implementing the SessionHandlerInterface or a configuration array. Default: null. | Session |
$hasSessionId | bool | Whether the current request has sent the session ID. | Session |
$id | string | The current session ID. | Session |
$isActive read-only | bool | Whether the session has started. | Session |
$iterator read-only | SessionIterator | An iterator for traversing the session variables. | Session |
$name | string | The current session name. | Session |
$savePath | string | The current session save path, defaults to ‘/tmp’. | Session |
$timeout | int | The number of seconds after which data will be seen as ‘garbage’ and cleaned up. | Session |
$useCookies | bool| | The value indicating whether cookies should be used to store session IDs. | Session |
$useCustomStorage read-only | bool | Whether to use custom storage. | Session |
$useStrictMode | bool | Whether strict mode is enabled or not. | Session |
$useTransparentSessionID | bool | Whether transparent sid support is enabled or not, defaults to false. | Session |
$_forceRegenerateId protected | string| | Holds the session id in case useStrictMode is enabled and the session id needs to be regenerated Default: null. | Session |
$_originalSessionModule protected static | string| | Holds 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 |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
addFlash() | Adds a flash message. | Session |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
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\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
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\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
getCacheLimiter() | Returns current cache limiter | Session |
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\ |
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\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
init() | Initializes the application component. | Session |
off() | Detaches an existing event handler from this component. | yii\ |
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\ |
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 limiter | Session |
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\ |
freeze() protected | If session is started it’s not possible to edit session ini settings. In PHP7.2+ it throws exception. | Session |
registerSessionHandler() protected | Registers session handler. | Session |
unfreeze() protected | Starts session and restores data from temporary variable | Session |
updateFlashCounters() protected | Updates the counters for flash messages and removes outdated flash messages. | Session |
Property details
Section titled “Property details”$flash
Section titled “$flash ”public string $flashThe 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).
$handler
Section titled “$handler ”public SessionHandlerInterface|array $handler = nullAn object implementing the SessionHandlerInterface or a configuration array.
If set, will be used to provide persistency instead of build-in methods.
$timeout
Section titled “$timeout ”public int $timeoutThe 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).
Method details
Section titled “Method details”addFlash()
Section titled “addFlash() ”public function addFlash(string $key, mixed $value = true, bool $removeAfterAccess = true): mixedAdds 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
| Parameter | Type | Description |
|---|---|---|
$key | string | The key identifying the flash message. |
$value | mixed | Flash message |
$removeAfterAccess | bool | Whether 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
close()
Section titled “close() ”public function close(): mixedEnds the current session and store session data.
Returns
mixed
count()
Section titled “count() ”public function count(): intReturns the number of items in the session.
This method is required by Countable interface.
Returns
int: Number of items in the session.
destroy()
Section titled “destroy() ”public function destroy(): mixedFrees 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.
get()
Section titled “get() ”public function get(string $key, mixed $defaultValue = null): mixedReturns the session variable value with the session variable name.
If the session variable does not exist, the $defaultValue will be returned.
Parameters
| Parameter | Type | Description |
|---|---|---|
$key | string | The session variable name |
$defaultValue | mixed | The 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.
getAllFlashes()
Section titled “getAllFlashes() ”public function getAllFlashes(bool $delete = false): arrayReturns all flash messages.
You may use this method to display all the flash messages in a view file:
<?phpforeach (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
| Parameter | Type | Description |
|---|---|---|
$delete | bool | Whether 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
getCacheLimiter()
Section titled “getCacheLimiter() ”public function getCacheLimiter(): stringReturns current cache limiter
Returns
string: Current cache limiter
Since
2.0.14
getCookieParams()
Section titled “getCookieParams() ”public function getCookieParams(): arrayReturns
array: The session cookie parameters.
See also
getCount()
Section titled “getCount() ”public function getCount(): intReturns the number of items in the session.
Returns
int: The number of session variables
getFlash()
Section titled “getFlash() ”public function getFlash(string $key, mixed $defaultValue = null, bool $delete = false): mixedReturns a flash message.
Parameters
| Parameter | Type | Description |
|---|---|---|
$key | string | The key identifying the flash message |
$defaultValue | mixed | Value to be returned if the flash message does not exist. |
$delete | bool | Whether 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
getGCProbability()
Section titled “getGCProbability() ”public function getGCProbability(): floatReturns
float: The probability (percentage) that the GC (garbage collection) process is started on every session initialization.
getHasSessionId()
Section titled “getHasSessionId() ”public function getHasSessionId(): boolReturns 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.
getId()
Section titled “getId() ”public function getId(): stringGets the session ID.
This is a wrapper for PHP session_id().
Returns
string: The current session ID
getIsActive()
Section titled “getIsActive() ”public function getIsActive(): boolReturns
bool: Whether the session has started
getIterator()
Section titled “getIterator() ”public function getIterator(): yii\web\SessionIteratorReturns an iterator for traversing the session variables.
This method is required by the interface IteratorAggregate.
Returns
SessionIterator: An iterator for traversing the session variables.
getName()
Section titled “getName() ”public function getName(): stringGets the name of the current session.
This is a wrapper for PHP session_name().
Returns
string: The current session name
getSavePath()
Section titled “getSavePath() ”public function getSavePath(): stringGets the current session save path.
This is a wrapper for PHP session_save_path().
Returns
string: The current session save path, defaults to ‘/tmp’.
getTimeout()
Section titled “getTimeout() ”public function getTimeout(): intReturns
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).
getUseCookies()
Section titled “getUseCookies() ”public function getUseCookies(): bool|nullReturns 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
getUseCustomStorage()
Section titled “getUseCustomStorage() ”public function getUseCustomStorage(): boolReturns 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.
getUseStrictMode()
Section titled “getUseStrictMode() ”public function getUseStrictMode(): boolgetUseTransparentSessionID()
Section titled “getUseTransparentSessionID() ”public function getUseTransparentSessionID(): boolReturns
bool: Whether transparent sid support is enabled or not, defaults to false.
has()
Section titled “has() ”public function has(mixed $key): boolParameters
| Parameter | Type | Description |
|---|---|---|
$key | mixed | Session variable name |
Returns
bool: Whether there is the named session variable
hasFlash()
Section titled “hasFlash() ”public function hasFlash(string $key): boolReturns a value indicating whether there are flash messages associated with the specified key.
Parameters
| Parameter | Type | Description |
|---|---|---|
$key | string | Key identifying the flash message type |
Returns
bool: Whether any flash messages exist under specified key
init()
Section titled “init() ”public function init(): mixedInitializes the application component.
This method is required by IApplicationComponent and is invoked by application.
Returns
mixed
offsetExists()
Section titled “offsetExists() ”public function offsetExists(int|string $offset): boolThis method is required by the interface ArrayAccess.
Parameters
| Parameter | Type | Description |
|---|---|---|
$offset | int| | The offset to check on |
Returns
bool
offsetGet()
Section titled “offsetGet() ”public function offsetGet(int|string $offset): mixedThis method is required by the interface ArrayAccess.
Parameters
| Parameter | Type | Description |
|---|---|---|
$offset | int| | The offset to retrieve element. |
Returns
mixed: The element at the offset, null if no element is found at the offset
offsetSet()
Section titled “offsetSet() ”public function offsetSet(int|string $offset, mixed $item): mixedThis method is required by the interface ArrayAccess.
Parameters
| Parameter | Type | Description |
|---|---|---|
$offset | int| | The offset to set element |
$item | mixed | The element value |
Returns
mixed
offsetUnset()
Section titled “offsetUnset() ”public function offsetUnset(int|string $offset): mixedThis method is required by the interface ArrayAccess.
Parameters
| Parameter | Type | Description |
|---|---|---|
$offset | int| | The offset to unset element |
Returns
mixed
regenerateID()
Section titled “regenerateID() ”public function regenerateID(bool $deleteOldSession = false): mixedUpdates 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.
remove()
Section titled “remove() ”public function remove(string $key): mixedRemoves a session variable.
Parameters
| Parameter | Type | Description |
|---|---|---|
$key | string | The name of the session variable to be removed |
Returns
mixed: The removed value, null if no such session variable.
removeAll()
Section titled “removeAll() ”public function removeAll(): mixedRemoves all session variables.
Returns
mixed
removeAllFlashes()
Section titled “removeAllFlashes() ”public function removeAllFlashes(): mixedRemoves 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.
removeFlash()
Section titled “removeFlash() ”public function removeFlash(string $key): mixedRemoves a flash message.
Parameters
| Parameter | Type | Description |
|---|---|---|
$key | string | 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, it will be removed by this method. |
Returns
mixed: The removed flash message. Null if the flash message does not exist.
See also
set()
Section titled “set() ”public function set(string $key, mixed $value): mixedAdds a session variable.
If the specified name already exists, the old value will be overwritten.
Parameters
| Parameter | Type | Description |
|---|---|---|
$key | string | Session variable name |
$value | mixed | Session variable value |
Returns
mixed
setCacheLimiter()
Section titled “setCacheLimiter() ”public function setCacheLimiter(string $cacheLimiter): mixedSet cache limiter
Parameters
| Parameter | Type | Description |
|---|---|---|
$cacheLimiter | string |
Returns
mixed
Since
2.0.14
setCookieParams()
Section titled “setCookieParams() ”public function setCookieParams(array $value): mixedSets the session cookie parameters.
The cookie parameters passed to this method will be merged with the result
of session_get_cookie_params().
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | array | Cookie 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
yii\base\InvalidArgumentException: if the parameters are incomplete.
See also
setFlash()
Section titled “setFlash() ”public function setFlash(string $key, mixed $value = true, bool $removeAfterAccess = true): mixedSets 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
| Parameter | Type | Description |
|---|---|---|
$key | string | 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. |
$value | mixed | Flash message |
$removeAfterAccess | bool | Whether 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
setGCProbability()
Section titled “setGCProbability() ”public function setGCProbability(float $value): mixedParameters
| Parameter | Type | Description |
|---|---|---|
$value | float | The probability (percentage) that the GC (garbage collection) process is started on every session initialization. |
Returns
mixed
Throws
yii\base\InvalidArgumentException: if the value is not between 0 and 100.
setHasSessionId()
Section titled “setHasSessionId() ”public function setHasSessionId(bool $value): mixedSets 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
| Parameter | Type | Description |
|---|---|---|
$value | bool | Whether the current request has sent the session ID. |
Returns
mixed
setId()
Section titled “setId() ”public function setId(string $value): mixedSets the session ID.
This is a wrapper for PHP session_id().
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string | The session ID for the current session |
Returns
mixed
setName()
Section titled “setName() ”public function setName(string $value): mixedSets the name for the current session.
This is a wrapper for PHP session_name().
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string | The session name for the current session, must be an alphanumeric string. It defaults to “PHPSESSID”. |
Returns
mixed
setSavePath()
Section titled “setSavePath() ”public function setSavePath(string $value): mixedSets the current session save path.
This is a wrapper for PHP session_save_path().
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | string | The current session save path. This can be either a directory name or a path alias. |
Returns
mixed
Throws
yii\base\InvalidArgumentException: if the path is not a valid directory
setTimeout()
Section titled “setTimeout() ”public function setTimeout(int $value): mixedParameters
| Parameter | Type | Description |
|---|---|---|
$value | int | The number of seconds after which data will be seen as ‘garbage’ and cleaned up |
Returns
mixed
setUseCookies()
Section titled “setUseCookies() ”public function setUseCookies(bool|null $value): mixedSets 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
| Parameter | Type | Description |
|---|---|---|
$value | bool| | The value indicating whether cookies should be used to store session IDs. |
Returns
mixed
setUseStrictMode()
Section titled “setUseStrictMode() ”public function setUseStrictMode(bool $value): mixedParameters
| Parameter | Type | Description |
|---|---|---|
$value | bool | Whether 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
setUseTransparentSessionID()
Section titled “setUseTransparentSessionID() ”public function setUseTransparentSessionID(bool $value): mixedParameters
| Parameter | Type | Description |
|---|---|---|
$value | bool | Whether transparent sid support is enabled or not. |
Returns
mixed
freeze()
Section titled “freeze() ”protected function freeze(): mixedIf 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
registerSessionHandler()
Section titled “registerSessionHandler() ”protected function registerSessionHandler(): mixedRegisters session handler.
unfreeze()
Section titled “unfreeze() ”protected function unfreeze(): mixedStarts session and restores data from temporary variable
Returns
mixed
Since
2.0.14
updateFlashCounters()
Section titled “updateFlashCounters() ”protected function updateFlashCounters(): mixedUpdates the counters for flash messages and removes outdated flash messages.
This method should only be called once in init().
Returns
mixed