没有命名空间的类 yii yii\base yii\behaviors yii\caching yii\captcha yii\console yii\console\controllers yii\console\widgets yii\data yii\db yii\db\conditions yii\db\cubrid yii\db\cubrid\conditions yii\db\mssql yii\db\mssql\conditions yii\db\mysql yii\db\oci yii\db\oci\conditions yii\db\pgsql yii\db\sqlite yii\db\sqlite\conditions yii\di yii\filters yii\filters\auth yii\grid yii\helpers yii\i18n yii\log yii\mail yii\mutex yii\rbac yii\rest yii\test yii\validators yii\web yii\widgets

Class yii\web\Session

继承yii\web\Session » yii\base\Component » yii\base\BaseObject
实现ArrayAccess, Countable, IteratorAggregate, yii\base\Configurable
子类yii\web\CacheSession, yii\web\DbSession, yii\web\MultiFieldSession
可用版本自2.0
源码 https://github.com/yiichina/yii2/blob/api/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.

公共属性

隐藏继承的属性

属性类型描述被定义在
$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

公共方法

隐藏继承的方法

方法描述被定义在
__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

受保护的方法

隐藏继承的方法

方法描述被定义在
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

属性详情

$allFlashes 公共 只读 属性

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

public array getAllFlashes ( $delete false )
$cacheLimiter 公共 属性
public string getCacheLimiter ( )
public void setCacheLimiter ( $cacheLimiter )
$cookieParams 公共 属性

The session cookie parameters.

public array getCookieParams ( )
public void setCookieParams ( array $value )
$count 公共 只读 属性

The number of session variables

public integer getCount ( )
$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.

public void setFlash ( $key, $value true, $removeAfterAccess true )
$flashParam 公共 属性

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

public string $flashParam '__flash'
$gCProbability 公共 属性

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 公共 属性

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

$hasSessionId 公共 属性

Whether the current request has sent the session ID.

public boolean getHasSessionId ( )
public void setHasSessionId ( $value )
$id 公共 属性

The current session ID

public string getId ( )
public void setId ( $value )
$isActive 公共 只读 属性

Whether the session has started

public boolean getIsActive ( )
$iterator 公共 只读 属性

An iterator for traversing the session variables.

$name 公共 属性

The current session name

public string getName ( )
public void setName ( $value )
$savePath 公共 属性

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

public string getSavePath ( )
public void setSavePath ( $value )
$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 integer getTimeout ( )
public void setTimeout ( $value )
$useCookies 公共 属性

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

public boolean|null getUseCookies ( )
public void setUseCookies ( $value )
$useCustomStorage 公共 只读 属性

Whether to use custom storage.

$useTransparentSessionID 公共 属性

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

方法详情

addFlash() 公共 方法

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.

参见:

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() 公共 方法

Ends the current session and store session data.

public void close()
closeSession() 公共 方法

Session close handler.

This method should be overridden if $useCustomStorage returns true.

public boolean closeSession()
return boolean

Whether session is closed successfully

count() 公共 方法

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() 公共 方法

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.

参见:

public void destroy()
destroySession() 公共 方法

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() 受保护 方法 (自版本 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() 公共 方法

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() 公共 方法

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() 公共 方法

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.

参见:

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() 公共 方法 (自版本 2.0.14 可用)

Returns current cache limiter

public string getCacheLimiter()
return string

Current cache limiter

getCookieParams() 公共 方法
public array getCookieParams()
return array

The session cookie parameters.

getCount() 公共 方法

Returns the number of items in the session.

public integer getCount()
return integer

The number of session variables

getFlash() 公共 方法
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 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() 公共 方法

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() 公共 方法

Gets the session ID.

This is a wrapper for PHP session_id().

public string getId()
return string

The current session ID

getIsActive() 公共 方法

public boolean getIsActive()
return boolean

Whether the session has started

getIterator() 公共 方法

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() 公共 方法

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() 公共 方法

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 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() 公共 方法

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

参见 setUseCookies().

public boolean|null getUseCookies()
return boolean|null

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

getUseCustomStorage() 公共 方法

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 boolean getUseTransparentSessionID()
return boolean

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

has() 公共 方法

public boolean has($key)
$key mixed

Session variable name

return boolean

Whether there is the named session variable

hasFlash() 公共 方法

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() 公共 方法

Initializes the application component.

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

public void init()
offsetExists() 公共 方法

This method is required by the interface ArrayAccess.

public boolean offsetExists($offset)
$offset mixed

The offset to check on

offsetGet() 公共 方法

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() 公共 方法

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() 公共 方法

This method is required by the interface ArrayAccess.

public void offsetUnset($offset)
$offset mixed

The offset to unset element

open() 公共 方法

Starts the session.

public void open()
openSession() 公共 方法

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() 公共 方法

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() 公共 方法

Updates the current session ID with a newly generated one.

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

参见:

public void regenerateID($deleteOldSession false)
$deleteOldSession boolean

Whether to delete the old associated session file or not.

registerSessionHandler() 受保护 方法

Registers session handler.

protected void registerSessionHandler()
throws yii\base\InvalidConfigException
remove() 公共 方法

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() 公共 方法

Removes all session variables.

public void removeAll()
removeAllFlashes() 公共 方法

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 void removeAllFlashes()
removeFlash() 公共 方法

Removes a flash message.

参见:

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() 公共 方法

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() 公共 方法 (自版本 2.0.14 可用)

Set cache limiter

public void setCacheLimiter($cacheLimiter)
$cacheLimiter string
setCookieParams() 公共 方法

Sets the session cookie parameters.

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

参见 http://us2.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() 公共 方法

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.

参见:

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 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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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 void setTimeout($value)
$value integer

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

setUseCookies() 公共 方法

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 void setUseTransparentSessionID($value)
$value boolean

Whether transparent sid support is enabled or not.

unfreeze() 受保护 方法 (自版本 2.0.14 可用)

Starts session and restores data from temporary variable

protected void unfreeze()
updateFlashCounters() 受保护 方法

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

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

protected void updateFlashCounters()
writeSession() 公共 方法

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