1 follower

Class yii\web\Session

Inheritanceyii\web\Session » yii\base\Component » yii\base\BaseObject
ImplementsArrayAccess, Countable, IteratorAggregate, yii\base\Configurable
Subclassesyii\web\CacheSession, yii\web\DbSession, yii\web\MultiFieldSession
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/web/Session.php

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.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$allFlashes array Flash messages (key => message or key => [message1, message2]). yii\web\Session
$behaviors yii\base\Behavior[] List of behaviors attached to this component yii\base\Component
$cacheLimiter string yii\web\Session
$cookieParams array The session cookie parameters. yii\web\Session
$count integer The number of session variables yii\web\Session
$flash string The key identifying the flash message. yii\web\Session
$flashParam string The name of the session variable that stores the flash message data. yii\web\Session
$gCProbability float The probability (percentage) that the GC (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance. yii\web\Session
$handler SessionHandlerInterface|array An object implementing the SessionHandlerInterface or a configuration array. yii\web\Session
$hasSessionId boolean Whether the current request has sent the session ID. yii\web\Session
$id string The current session ID yii\web\Session
$isActive boolean Whether the session has started yii\web\Session
$iterator yii\web\SessionIterator An iterator for traversing the session variables. yii\web\Session
$name string The current session name yii\web\Session
$savePath string The current session save path, defaults to '/tmp'. yii\web\Session
$timeout integer The number of seconds after which data will be seen as 'garbage' and cleaned up. yii\web\Session
$useCookies boolean|null The value indicating whether cookies should be used to store session IDs. yii\web\Session
$useCustomStorage boolean Whether to use custom storage. yii\web\Session
$useTransparentSessionID boolean Whether transparent sid support is enabled or not, defaults to false. yii\web\Session

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__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
__construct() Constructor. yii\base\BaseObject
__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. yii\web\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() Returns the fully qualified name of this class. yii\base\BaseObject
close() Ends the current session and store session data. yii\web\Session
closeSession() Session close handler. yii\web\Session
count() Returns the number of items in the session. yii\web\Session
destroy() Frees all session variables and destroys all data registered to a session. yii\web\Session
destroySession() Session destroy handler. yii\web\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
gcSession() Session GC (garbage collection) handler. yii\web\Session
get() Returns the session variable value with the session variable name. yii\web\Session
getAllFlashes() Returns all flash messages. yii\web\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 limiter yii\web\Session
getCookieParams() yii\web\Session
getCount() Returns the number of items in the session. yii\web\Session
getFlash() Returns a flash message. yii\web\Session
getGCProbability() yii\web\Session
getHasSessionId() Returns a value indicating whether the current request has sent the session ID. yii\web\Session
getId() Gets the session ID. yii\web\Session
getIsActive() yii\web\Session
getIterator() Returns an iterator for traversing the session variables. yii\web\Session
getName() Gets the name of the current session. yii\web\Session
getSavePath() Gets the current session save path. yii\web\Session
getTimeout() yii\web\Session
getUseCookies() Returns the value indicating whether cookies should be used to store session IDs. yii\web\Session
getUseCustomStorage() Returns a value indicating whether to use custom session storage. yii\web\Session
getUseTransparentSessionID() yii\web\Session
has() yii\web\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. yii\web\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. yii\web\Session
off() Detaches an existing event handler from this component. yii\base\Component
offsetExists() This method is required by the interface ArrayAccess. yii\web\Session
offsetGet() This method is required by the interface ArrayAccess. yii\web\Session
offsetSet() This method is required by the interface ArrayAccess. yii\web\Session
offsetUnset() This method is required by the interface ArrayAccess. yii\web\Session
on() Attaches an event handler to an event. yii\base\Component
open() Starts the session. yii\web\Session
openSession() Session open handler. yii\web\Session
readSession() Session read handler. yii\web\Session
regenerateID() Updates the current session ID with a newly generated one. yii\web\Session
remove() Removes a session variable. yii\web\Session
removeAll() Removes all session variables. yii\web\Session
removeAllFlashes() Removes all flash messages. yii\web\Session
removeFlash() Removes a flash message. yii\web\Session
set() Adds a session variable. yii\web\Session
setCacheLimiter() Set cache limiter yii\web\Session
setCookieParams() Sets the session cookie parameters. yii\web\Session
setFlash() Sets a flash message. yii\web\Session
setGCProbability() yii\web\Session
setHasSessionId() Sets the value indicating whether the current request has sent the session ID. yii\web\Session
setId() Sets the session ID. yii\web\Session
setName() Sets the name for the current session. yii\web\Session
setSavePath() Sets the current session save path. yii\web\Session
setTimeout() yii\web\Session
setUseCookies() Sets the value indicating whether cookies should be used to store session IDs. yii\web\Session
setUseTransparentSessionID() yii\web\Session
trigger() Triggers an event. yii\base\Component
writeSession() Session write handler. yii\web\Session

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
freeze() If session is started it's not possible to edit session ini settings. In PHP7.2+ it throws exception. yii\web\Session
registerSessionHandler() Registers session handler. yii\web\Session
unfreeze() Starts session and restores data from temporary variable yii\web\Session
updateFlashCounters() Updates the counters for flash messages and removes outdated flash messages. yii\web\Session

Property Details

$allFlashes public read-only property

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

public array getAllFlashes ( $delete false )
$cacheLimiter public property
public string getCacheLimiter ( )
public void setCacheLimiter ( $cacheLimiter )
$cookieParams public property

The session cookie parameters.

public array getCookieParams ( )
public void setCookieParams ( array $value )
$count public read-only property

The number of session variables

public integer getCount ( )
$flash public write-only property

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.

public void setFlash ( $key, $value true, $removeAfterAccess true )
$flashParam public property

The name of the session variable that stores the flash message data.

public string $flashParam '__flash'
$gCProbability public property

The probability (percentage) that the GC (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.

public float getGCProbability ( )
public void setGCProbability ( $value )
$handler public property

An object implementing the SessionHandlerInterface or a configuration array. If set, will be used to provide persistency instead of build-in methods.

$hasSessionId public property

Whether the current request has sent the session ID.

public boolean getHasSessionId ( )
public void setHasSessionId ( $value )
$id public property

The current session ID

public string getId ( )
public void setId ( $value )
$isActive public read-only property

Whether the session has started

public boolean getIsActive ( )
$iterator public read-only property

An iterator for traversing the session variables.

$name public property

The current session name

public string getName ( )
public void setName ( $value )
$savePath public property

The current session save path, defaults to '/tmp'.

public string getSavePath ( )
public void setSavePath ( $value )
$timeout public property

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 integer getTimeout ( )
public void setTimeout ( $value )
$useCookies public property

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

public boolean|null getUseCookies ( )
public void setUseCookies ( $value )
$useCustomStorage public read-only property

Whether to use custom storage.

$useTransparentSessionID public property

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

Method Details

addFlash() public method

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.

See also:

public void addFlash ( $key, $value true, $removeAfterAccess true )
$key string

The key identifying the flash message.

$value mixed

Flash message

$removeAfterAccess boolean

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.

close() public method

Ends the current session and store session data.

public void close ( )
closeSession() public method

Session close handler.

This method should be overridden if $useCustomStorage returns true.

public boolean closeSession ( )
return boolean

Whether session is closed successfully

count() public method

Returns the number of items in the session.

This method is required by Countable interface.

public integer count ( )
return integer

Number of items in the session.

destroy() public method

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.

See also:

public void destroy ( )
destroySession() public method

Session destroy handler.

This method should be overridden if $useCustomStorage returns true.

public boolean destroySession ( $id )
$id string

Session ID

return boolean

Whether session is destroyed successfully

freeze() protected method (available since version 2.0.14)

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.

protected void freeze ( )
gcSession() public method

Session GC (garbage collection) handler.

This method should be overridden if $useCustomStorage returns true.

public boolean gcSession ( $maxLifetime )
$maxLifetime integer

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

return boolean

Whether session is GCed successfully

get() public method

Returns the session variable value with the session variable name.

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

public mixed get ( $key, $defaultValue null )
$key string

The session variable name

$defaultValue mixed

The default value to be returned when the session variable does not exist.

return mixed

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

getAllFlashes() public method

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 '<div class="alert alert-' . $key . '">' . $message . '</div>';
} ?>

With the above code you can use the bootstrap alert classes such as success, info, danger as the flash message key to influence the color of the div.

Note that if you use addFlash(), $message will be an array, and you will have to adjust the above code.

See also:

public array getAllFlashes ( $delete false )
$delete boolean

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.

return array

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

getCacheLimiter() public method (available since version 2.0.14)

Returns current cache limiter

public string getCacheLimiter ( )
return string

Current cache limiter

getCookieParams() public method
public array getCookieParams ( )
return array

The session cookie parameters.

getCount() public method

Returns the number of items in the session.

public integer getCount ( )
return integer

The number of session variables

getFlash() public method
public mixed getFlash ( $key, $defaultValue null, $delete false )
$key string

The key identifying the flash message

$defaultValue mixed

Value to be returned if the flash message does not exist.

$delete boolean

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.

return mixed

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

getGCProbability() public method

public float getGCProbability ( )
return float

The probability (percentage) that the GC (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.

getHasSessionId() public method

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.

public boolean getHasSessionId ( )
return boolean

Whether the current request has sent the session ID.

getId() public method

Gets the session ID.

This is a wrapper for PHP session_id().

public string getId ( )
return string

The current session ID

getIsActive() public method

public boolean getIsActive ( )
return boolean

Whether the session has started

getIterator() public method

Returns an iterator for traversing the session variables.

This method is required by the interface IteratorAggregate.

public yii\web\SessionIterator getIterator ( )
return yii\web\SessionIterator

An iterator for traversing the session variables.

getName() public method

Gets the name of the current session.

This is a wrapper for PHP session_name().

public string getName ( )
return string

The current session name

getSavePath() public method

Gets the current session save path.

This is a wrapper for PHP session_save_path().

public string getSavePath ( )
return string

The current session save path, defaults to '/tmp'.

getTimeout() public method

public integer getTimeout ( )
return integer

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() public method

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

See also setUseCookies().

public boolean|null getUseCookies ( )
return boolean|null

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

getUseCustomStorage() public method

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().

public boolean getUseCustomStorage ( )
return boolean

Whether to use custom storage.

getUseTransparentSessionID() public method

public boolean getUseTransparentSessionID ( )
return boolean

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

has() public method

public boolean has ( $key )
$key mixed

Session variable name

return boolean

Whether there is the named session variable

hasFlash() public method

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

public boolean hasFlash ( $key )
$key string

Key identifying the flash message type

return boolean

Whether any flash messages exist under specified key

init() public method

Initializes the application component.

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

public void init ( )
offsetExists() public method

This method is required by the interface ArrayAccess.

public boolean offsetExists ( $offset )
$offset mixed

The offset to check on

offsetGet() public method

This method is required by the interface ArrayAccess.

public mixed offsetGet ( $offset )
$offset integer

The offset to retrieve element.

return mixed

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

offsetSet() public method

This method is required by the interface ArrayAccess.

public void offsetSet ( $offset, $item )
$offset integer

The offset to set element

$item mixed

The element value

offsetUnset() public method

This method is required by the interface ArrayAccess.

public void offsetUnset ( $offset )
$offset mixed

The offset to unset element

open() public method

Starts the session.

public void open ( )
openSession() public method

Session open handler.

This method should be overridden if $useCustomStorage returns true.

public boolean openSession ( $savePath, $sessionName )
$savePath string

Session save path

$sessionName string

Session name

return boolean

Whether session is opened successfully

readSession() public method

Session read handler.

This method should be overridden if $useCustomStorage returns true.

public string readSession ( $id )
$id string

Session ID

return string

The session data

regenerateID() public method

Updates the current session ID with a newly generated one.

Please refer to https://secure.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.

See also:

public void regenerateID ( $deleteOldSession false )
$deleteOldSession boolean

Whether to delete the old associated session file or not.

registerSessionHandler() protected method

Registers session handler.

protected void registerSessionHandler ( )
throws yii\base\InvalidConfigException
remove() public method

Removes a session variable.

public mixed remove ( $key )
$key string

The name of the session variable to be removed

return mixed

The removed value, null if no such session variable.

removeAll() public method

Removes all session variables.

public void removeAll ( )
removeAllFlashes() public method

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.

See also:

public void removeAllFlashes ( )
removeFlash() public method

Removes a flash message.

See also:

public mixed removeFlash ( $key )
$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.

return mixed

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

set() public method

Adds a session variable.

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

public void set ( $key, $value )
$key string

Session variable name

$value mixed

Session variable value

setCacheLimiter() public method (available since version 2.0.14)

Set cache limiter

public void setCacheLimiter ( $cacheLimiter )
$cacheLimiter string
setCookieParams() public method

Sets the session cookie parameters.

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

See also https://secure.php.net/manual/en/function.session-set-cookie-params.php.

public void setCookieParams ( array $value )
$value array

Cookie parameters, valid keys include: lifetime, path, domain, secure and httponly.

throws yii\base\InvalidArgumentException

if the parameters are incomplete.

setFlash() public method

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.

See also:

public void setFlash ( $key, $value true, $removeAfterAccess true )
$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 boolean

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.

setGCProbability() public method

public void setGCProbability ( $value )
$value float

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

throws yii\base\InvalidArgumentException

if the value is not between 0 and 100.

setHasSessionId() public method

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.

public void setHasSessionId ( $value )
$value boolean

Whether the current request has sent the session ID.

setId() public method

Sets the session ID.

This is a wrapper for PHP session_id().

public void setId ( $value )
$value string

The session ID for the current session

setName() public method

Sets the name for the current session.

This is a wrapper for PHP session_name().

public void setName ( $value )
$value string

The session name for the current session, must be an alphanumeric string. It defaults to "PHPSESSID".

setSavePath() public method

Sets the current session save path.

This is a wrapper for PHP session_save_path().

public void setSavePath ( $value )
$value string

The current session save path. This can be either a directory name or a path alias.

throws yii\base\InvalidArgumentException

if the path is not a valid directory

setTimeout() public method

public void setTimeout ( $value )
$value integer

The number of seconds after which data will be seen as 'garbage' and cleaned up

setUseCookies() public method

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)
public void setUseCookies ( $value )
$value boolean|null

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

setUseTransparentSessionID() public method

public void setUseTransparentSessionID ( $value )
$value boolean

Whether transparent sid support is enabled or not.

unfreeze() protected method (available since version 2.0.14)

Starts session and restores data from temporary variable

protected void unfreeze ( )
updateFlashCounters() protected method

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

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

protected void updateFlashCounters ( )
writeSession() public method

Session write handler.

This method should be overridden if $useCustomStorage returns true.

public boolean writeSession ( $id, $data )
$id string

Session ID

$data string

Session data

return boolean

Whether session write is successful