Class yii\web\Session
Inheritance | yii\web\Session » yii\base\Component » yii\base\Object |
---|---|
Implements | ArrayAccess, Countable, IteratorAggregate, yii\base\Configurable |
Subclasses | yii\mongodb\Session, yii\redis\Session, yii\web\CacheSession, yii\web\DbSession, yii\web\MultiFieldSession |
Available since version | 2.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().
Public Properties
Property | Type | Description | Defined 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 |
$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
Method | Description | Defined 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\Object |
__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\Object |
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 |
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 |
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
Method | Description | Defined By |
---|---|---|
registerSessionHandler() | Registers session handler. | yii\web\Session |
updateFlashCounters() | Updates the counters for flash messages and removes outdated flash messages. | yii\web\Session |
Property Details
Flash messages (key => message or key => [message1, message2]).
The session cookie parameters.
The number of session variables
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.
The name of the session variable that stores the flash message data.
The probability (percentage) that the GC (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.
An object implementing the SessionHandlerInterface or a configuration array. If set, will be used to provide persistency instead of build-in methods.
Whether the current request has sent the session ID.
The current session ID
Whether the session has started
An iterator for traversing the session variables.
The current session name
The current session save path, defaults to '/tmp'.
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).
The value indicating whether cookies should be used to store session IDs.
Whether to use custom storage.
Whether transparent sid support is enabled or not, defaults to false.
Method Details
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:
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. |
Ends the current session and store session data.
void close( ) |
Session close handler.
This method should be overridden if $useCustomStorage returns true. Do not call this method directly.
boolean closeSession( ) | ||
return | boolean | Whether session is closed successfully |
---|
Returns the number of items in the session.
This method is required by Countable interface.
integer count( ) | ||
return | integer | Number of items in the session. |
---|
Frees all session variables and destroys all data registered to a session.
void destroy( ) |
Session destroy handler.
This method should be overridden if $useCustomStorage returns true. Do not call this method directly.
boolean destroySession( $id ) | ||
$id | string | Session ID |
return | boolean | Whether session is destroyed successfully |
---|
Session GC (garbage collection) handler.
This method should be overridden if $useCustomStorage returns true. Do not call this method directly.
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 |
---|
Returns the session variable value with the session variable name.
If the session variable does not exist, the $defaultValue
will be returned.
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. |
---|
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:
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]). |
---|
array getCookieParams( ) | ||
return | array | The session cookie parameters. |
---|
Returns the number of items in the session.
integer getCount( ) | ||
return | integer | The number of session variables |
---|
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 |
---|
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. |
---|
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.
boolean getHasSessionId( ) | ||
return | boolean | Whether the current request has sent the session ID. |
---|
Gets the session ID.
This is a wrapper for PHP session_id().
string getId( ) | ||
return | string | The current session ID |
---|
boolean getIsActive( ) | ||
return | boolean | Whether the session has started |
---|
Returns an iterator for traversing the session variables.
This method is required by the interface IteratorAggregate.
yii\web\SessionIterator getIterator( ) | ||
return | yii\web\SessionIterator | An iterator for traversing the session variables. |
---|
Gets the name of the current session.
This is a wrapper for PHP session_name().
string getName( ) | ||
return | string | The current session name |
---|
Gets the current session save path.
This is a wrapper for PHP session_save_path().
string getSavePath( ) | ||
return | string | The current session save path, defaults to '/tmp'. |
---|
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). |
---|
Returns the value indicating whether cookies should be used to store session IDs.
See also setUseCookies().
boolean|null getUseCookies( ) | ||
return | boolean|null | The value indicating whether cookies should be used to store session IDs. |
---|
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().
boolean getUseCustomStorage( ) | ||
return | boolean | Whether to use custom storage. |
---|
boolean getUseTransparentSessionID( ) | ||
return | boolean | Whether transparent sid support is enabled or not, defaults to false. |
---|
boolean has( $key ) | ||
$key | mixed | Session variable name |
return | boolean | Whether there is the named session variable |
---|
Returns a value indicating whether there are flash messages associated with the specified key.
boolean hasFlash( $key ) | ||
$key | string | Key identifying the flash message type |
return | boolean | Whether any flash messages exist under specified key |
---|
Initializes the application component.
This method is required by IApplicationComponent and is invoked by application.
void init( ) |
This method is required by the interface ArrayAccess.
boolean offsetExists( $offset ) | ||
$offset | mixed | The offset to check on |
This method is required by the interface ArrayAccess.
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 |
---|
This method is required by the interface ArrayAccess.
void offsetSet( $offset, $item ) | ||
$offset | integer | The offset to set element |
$item | mixed | The element value |
This method is required by the interface ArrayAccess.
void offsetUnset( $offset ) | ||
$offset | mixed | The offset to unset element |
Starts the session.
void open( ) |
Session open handler.
This method should be overridden if $useCustomStorage returns true. Do not call this method directly.
boolean openSession( $savePath, $sessionName ) | ||
$savePath | string | Session save path |
$sessionName | string | Session name |
return | boolean | Whether session is opened successfully |
---|
Session read handler.
This method should be overridden if $useCustomStorage returns true. Do not call this method directly.
string readSession( $id ) | ||
$id | string | Session ID |
return | string | The session data |
---|
Updates the current session ID with a newly generated one .
Please refer to http://php.net/session_regenerate_id for more details.
void regenerateID( $deleteOldSession = false ) | ||
$deleteOldSession | boolean | Whether to delete the old associated session file or not. |
Registers session handler.
void registerSessionHandler( ) | ||
throws | yii\base\InvalidConfigException |
---|
Removes a session variable.
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. |
---|
Removes all session variables
void removeAll( ) |
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:
void removeAllFlashes( ) |
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. |
---|
Adds a session variable.
If the specified name already exists, the old value will be overwritten.
void set( $key, $value ) | ||
$key | string | Session variable name |
$value | mixed | Session variable value |
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 http://us2.php.net/manual/en/function.session-set-cookie-params.php.
void setCookieParams( array $value ) | ||
$value | array | Cookie parameters, valid keys include: |
throws | yii\base\InvalidParamException | if the parameters are incomplete. |
---|
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:
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. |
void setGCProbability( $value ) | ||
$value | float | The probability (percentage) that the GC (garbage collection) process is started on every session initialization. |
throws | yii\base\InvalidParamException | if the value is not between 0 and 100. |
---|
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.
void setHasSessionId( $value ) | ||
$value | boolean | Whether the current request has sent the session ID. |
Sets the session ID.
This is a wrapper for PHP session_id().
void setId( $value ) | ||
$value | string | The session ID for the current session |
Sets the name for the current session.
This is a wrapper for PHP session_name().
void setName( $value ) | ||
$value | string | The session name for the current session, must be an alphanumeric string. It defaults to "PHPSESSID". |
Sets the current session save path.
This is a wrapper for PHP session_save_path().
void setSavePath( $value ) | ||
$value | string | The current session save path. This can be either a directory name or a path alias. |
throws | yii\base\InvalidParamException | if the path is not a valid directory |
---|
void setTimeout( $value ) | ||
$value | integer | The number of seconds after which data will be seen as 'garbage' and cleaned up |
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)
void setUseCookies( $value ) | ||
$value | boolean|null | The value indicating whether cookies should be used to store session IDs. |
void setUseTransparentSessionID( $value ) | ||
$value | boolean | Whether transparent sid support is enabled or not. |
Updates the counters for flash messages and removes outdated flash messages.
This method should only be called once in init().
void updateFlashCounters( ) |
Session write handler.
This method should be overridden if $useCustomStorage returns true. Do not call this method directly.
boolean writeSession( $id, $data ) | ||
$id | string | Session ID |
$data | string | Session data |
return | boolean | Whether session write is successful |
---|