Class yii\web\DbSession
Inheritance | yii\web\DbSession » yii\web\MultiFieldSession » yii\web\Session » yii\base\Component » yii\base\BaseObject |
---|---|
Implements | ArrayAccess, Countable, IteratorAggregate, yii\base\Configurable |
Available since version | 2.0 |
Source Code | https://github.com/yiisoft/yii2/blob/master/framework/web/DbSession.php |
DbSession extends yii\web\Session by using database as session data storage.
By default, DbSession stores session data in a DB table named 'session'. This table must be pre-created. The table name can be changed by setting $sessionTable.
The following example shows how you can configure the application to use DbSession:
Add the following to your application config under components
:
'session' => [
'class' => 'yii\web\DbSession',
// 'db' => 'mydb',
// 'sessionTable' => 'my_session',
]
DbSession extends yii\web\MultiFieldSession, thus it allows saving extra fields into the $sessionTable. Refer to yii\web\MultiFieldSession for more details.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$_forceRegenerateId | string|null | Holds the session id in case useStrictMode is enabled and the session id needs to be regenerated | yii\web\Session |
$_originalSessionModule | string|null | 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. | yii\web\Session |
$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 | Current cache limiter. | yii\web\Session |
$cookieParams | array | The session cookie parameters. | yii\web\Session |
$count | integer | The number of session variables. | yii\web\Session |
$db | yii\db\Connection|array|string | The DB connection object or the application component ID of the DB connection. | yii\web\DbSession |
$fields | array | Session fields to be written into session table columns | yii\web\DbSession |
$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. | 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 |
$readCallback | callable | A callback that will be called during session data reading. | yii\web\MultiFieldSession |
$savePath | string | The current session save path, defaults to '/tmp'. | yii\web\Session |
$sessionTable | string | The name of the DB table that stores the session data. | yii\web\DbSession |
$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\MultiFieldSession |
$useStrictMode | boolean | Whether strict mode is enabled or not. | yii\web\Session |
$useTransparentSessionID | boolean | Whether transparent sid support is enabled or not, defaults to false. | yii\web\Session |
$writeCallback | callable | A callback that will be called during session data writing. | yii\web\MultiFieldSession |
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\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\DbSession |
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 |
detachBehavior() | Detaches a behavior from the component. | yii\base\Component |
detachBehaviors() | Detaches all behaviors from the component. | yii\base\Component |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\base\Component |
get() | Returns the session variable value with the session variable name. | 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\MultiFieldSession |
getUseStrictMode() | 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 DbSession component. | yii\web\DbSession |
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 |
regenerateID() | Updates the current session ID with a newly generated one. | yii\web\DbSession |
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 |
setUseStrictMode() | yii\web\Session | |
setUseTransparentSessionID() | yii\web\Session | |
trigger() | Triggers an event. | yii\base\Component |
Protected Methods
Method | Description | Defined By |
---|---|---|
composeFields() | Composes storage field set for session writing. | yii\web\MultiFieldSession |
extractData() | Extracts session data from storage field set. | yii\web\MultiFieldSession |
freeze() | If session is started it's not possible to edit session ini settings. In PHP7.2+ it throws exception. | yii\web\Session |
getReadQuery() | Generates a query to get the session from db | yii\web\DbSession |
registerSessionHandler() | Registers session handler. | yii\web\Session |
typecastFields() | Method typecasts $fields before passing them to PDO. | yii\web\DbSession |
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
The DB connection object or the application component ID of the DB connection. After the DbSession object is created, if you want to change this property, you should only assign it with a DB connection object. Starting from version 2.0.2, this can also be a configuration array for creating the object.
Session fields to be written into session table columns
The name of the DB table that stores the session data. The table should be pre-created as follows:
CREATE TABLE session
(
id CHAR(40) NOT NULL PRIMARY KEY,
expire INTEGER,
data BLOB
)
where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB type that can be used for some popular DBMS:
- MySQL: LONGBLOB
- PostgreSQL: BYTEA
- MSSQL: BLOB
When using DbSession in a production server, we recommend you create a DB index for the 'expire' column in the session table to improve the performance.
Note that according to the php.ini setting of session.hash_function
, you may need to adjust
the length of the id
column. For example, if session.hash_function=sha256
, you should use
length 64 instead of 40.
Method Details
Defined in: yii\base\Component::__call()
Calls the named method which is not a class method.
This method will check if any attached behavior has the named method and will execute it if available.
Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.
public mixed __call ( $name, $params ) | ||
$name | string |
The method name |
$params | array |
Method parameters |
return | mixed |
The method return value |
---|---|---|
throws | yii\base\UnknownMethodException |
when calling unknown method |
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
Defined in: yii\base\Component::__clone()
This method is called after the object is created by cloning an existing one.
It removes all behaviors because they are attached to the old object.
public void __clone ( ) |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
Defined in: yii\base\BaseObject::__construct()
Constructor.
The default implementation does two things:
- Initializes the object with the given configuration
$config
. - Call init().
If this method is overridden in a child class, it is recommended that
- the last parameter of the constructor is a configuration array, like
$config
here. - call the parent implementation at the end of the constructor.
public void __construct ( $config = [] ) | ||
$config | array |
Name-value pairs that will be used to initialize the object properties |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
Defined in: yii\base\Component::__get()
Returns the value of a component property.
This method will check in the following order and act accordingly:
- a property defined by a getter: return the getter result
- a property of a behavior: return the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $value = $component->property;
.
See also __set().
public mixed __get ( $name ) | ||
$name | string |
The property name |
return | mixed |
The property value or the value of a behavior's property |
---|---|---|
throws | yii\base\UnknownPropertyException |
if the property is not defined |
throws | yii\base\InvalidCallException |
if the property is write-only. |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__isset()
Checks if a property is set, i.e. defined and not null.
This method will check in the following order and act accordingly:
- a property defined by a setter: return whether the property is set
- a property of a behavior: return whether the property is set
- return
false
for non existing properties
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing isset($component->property)
.
public boolean __isset ( $name ) | ||
$name | string |
The property name or the event name |
return | boolean |
Whether the named property is set |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name !== null;
}
}
return false;
}
Defined in: yii\base\Component::__set()
Sets the value of a component property.
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value
- an event in the format of "on xyz": attach the handler to the event "xyz"
- a behavior in the format of "as xyz": attach the behavior named as "xyz"
- a property of a behavior: set the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $component->property = $value;
.
See also __get().
public void __set ( $name, $value ) | ||
$name | string |
The property name or the event name |
$value | mixed |
The property value |
throws | yii\base\UnknownPropertyException |
if the property is not defined |
---|---|---|
throws | yii\base\InvalidCallException |
if the property is read-only. |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__unset()
Sets a component property to be null.
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value to be null
- a property of a behavior: set the property value to be null
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing unset($component->property)
.
public void __unset ( $name ) | ||
$name | string |
The property name |
throws | yii\base\InvalidCallException |
if the property is read only. |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\web\Session::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.
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. |
public function addFlash($key, $value = true, $removeAfterAccess = true)
{
$counters = $this->get($this->flashParam, []);
$counters[$key] = $removeAfterAccess ? -1 : 0;
$_SESSION[$this->flashParam] = $counters;
if (empty($_SESSION[$key])) {
$_SESSION[$key] = [$value];
} elseif (is_array($_SESSION[$key])) {
$_SESSION[$key][] = $value;
} else {
$_SESSION[$key] = [$_SESSION[$key], $value];
}
}
Defined in: yii\base\Component::attachBehavior()
Attaches a behavior to this component.
This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the yii\base\Behavior::attach() method.
See also detachBehavior().
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
The name of the behavior. |
$behavior | string|array|yii\base\Behavior |
The behavior configuration. This can be one of the following:
|
return | yii\base\Behavior |
The behavior object |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
Defined in: yii\base\Component::attachBehaviors()
Attaches a list of behaviors to the component.
Each behavior is indexed by its name and should be a yii\base\Behavior object, a string specifying the behavior class, or an configuration array for creating the behavior.
See also attachBehavior().
public void attachBehaviors ( $behaviors ) | ||
$behaviors | array |
List of behaviors to be attached to the component |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
Defined in: yii\base\Component::behaviors()
Returns a list of behaviors that this component should behave as.
Child classes may override this method to specify the behaviors they want to behave as.
The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
Note that a behavior class must extend from yii\base\Behavior. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using getBehavior() or be detached using detachBehavior(). Anonymous behaviors can not be retrieved or detached.
Behaviors declared in this method will be attached to the component automatically (on demand).
public array behaviors ( ) | ||
return | array |
The behavior configurations. |
---|
public function behaviors()
{
return [];
}
Defined in: yii\base\Component::canGetProperty()
Returns a value indicating whether a property can be read.
A property can be read if:
- the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a readable property of the given name (when
$checkBehaviors
is true).
See also canSetProperty().
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property can be read |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::canSetProperty()
Returns a value indicating whether a property can be set.
A property can be written if:
- the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a writable property of the given name (when
$checkBehaviors
is true).
See also canGetProperty().
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property can be written |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
::class
instead.
Defined in: yii\base\BaseObject::className()
Returns the fully qualified name of this class.
public static string className ( ) | ||
return | string |
The fully qualified name of this class. |
---|
public static function className()
{
return get_called_class();
}
Ends the current session and store session data.
public void close ( ) |
public function close()
{
if ($this->getIsActive()) {
// prepare writeCallback fields before session closes
$this->fields = $this->composeFields();
YII_DEBUG ? session_write_close() : @session_write_close();
}
}
Defined in: yii\web\MultiFieldSession::composeFields()
Composes storage field set for session writing.
protected array composeFields ( $id = null, $data = null ) | ||
$id | string|null |
Optional session id |
$data | string|null |
Optional session data |
return | array |
Storage fields |
---|
protected function composeFields($id = null, $data = null)
{
$fields = $this->writeCallback ? call_user_func($this->writeCallback, $this) : [];
if ($id !== null) {
$fields['id'] = $id;
}
if ($data !== null) {
$fields['data'] = $data;
}
return $fields;
}
Defined in: yii\web\Session::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. |
---|
#[\ReturnTypeWillChange]
public function count()
{
return $this->getCount();
}
Defined in: yii\web\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.
See also:
public void destroy ( ) |
public function destroy()
{
if ($this->getIsActive()) {
$sessionId = session_id();
$this->close();
$this->setId($sessionId);
$this->open();
session_unset();
session_destroy();
$this->setId($sessionId);
}
}
Defined in: yii\base\Component::detachBehavior()
Detaches a behavior from the component.
The behavior's yii\base\Behavior::detach() method will be invoked.
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
The behavior's name. |
return | yii\base\Behavior|null |
The detached behavior. Null if the behavior does not exist. |
---|
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
Defined in: yii\base\Component::detachBehaviors()
Detaches all behaviors from the component.
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
Defined in: yii\base\Component::ensureBehaviors()
Makes sure that the behaviors declared in behaviors() are attached to this component.
public void ensureBehaviors ( ) |
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
Defined in: yii\web\MultiFieldSession::extractData()
Extracts session data from storage field set.
protected string extractData ( $fields ) | ||
$fields | array |
Storage fields. |
return | string |
Session data. |
---|
protected function extractData($fields)
{
if ($this->readCallback !== null) {
if (!isset($fields['data'])) {
$fields['data'] = '';
}
$extraData = call_user_func($this->readCallback, $fields);
if (!empty($extraData)) {
session_decode($fields['data']);
$_SESSION = array_merge((array) $_SESSION, (array) $extraData);
return session_encode();
}
return $fields['data'];
}
return isset($fields['data']) ? $fields['data'] : '';
}
Defined in: yii\web\Session::freeze()
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 ( ) |
protected function freeze()
{
if ($this->getIsActive()) {
if (isset($_SESSION)) {
$this->_frozenSessionData = $_SESSION;
}
$this->close();
Yii::info('Session frozen', __METHOD__);
}
}
Defined in: yii\web\Session::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. |
---|
public function get($key, $defaultValue = null)
{
$this->open();
return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
}
Defined in: yii\web\Session::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.
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]). |
---|
public function getAllFlashes($delete = false)
{
$counters = $this->get($this->flashParam, []);
$flashes = [];
foreach (array_keys($counters) as $key) {
if (array_key_exists($key, $_SESSION)) {
$flashes[$key] = $_SESSION[$key];
if ($delete) {
unset($counters[$key], $_SESSION[$key]);
} elseif ($counters[$key] < 0) {
// mark for deletion in the next request
$counters[$key] = 1;
}
} else {
unset($counters[$key]);
}
}
$_SESSION[$this->flashParam] = $counters;
return $flashes;
}
Defined in: yii\base\Component::getBehavior()
Returns the named behavior object.
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | string |
The behavior name |
return | yii\base\Behavior|null |
The behavior object, or null if the behavior does not exist |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
Defined in: yii\base\Component::getBehaviors()
Returns all behaviors attached to this component.
public yii\base\Behavior[] getBehaviors ( ) | ||
return | yii\base\Behavior[] |
List of behaviors attached to this component |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
Defined in: yii\web\Session::getCacheLimiter()
Returns current cache limiter
public string getCacheLimiter ( ) | ||
return | string |
Current cache limiter |
---|
public function getCacheLimiter()
{
return session_cache_limiter();
}
Defined in: yii\web\Session::getCookieParams()
See also https://www.php.net/manual/en/function.session-get-cookie-params.php.
public array getCookieParams ( ) | ||
return | array |
The session cookie parameters. |
---|
public function getCookieParams()
{
return array_merge(session_get_cookie_params(), array_change_key_case($this->_cookieParams));
}
Defined in: yii\web\Session::getCount()
Returns the number of items in the session.
public integer getCount ( ) | ||
return | integer |
The number of session variables |
---|
public function getCount()
{
$this->open();
return count($_SESSION);
}
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 |
---|
public function getFlash($key, $defaultValue = null, $delete = false)
{
$counters = $this->get($this->flashParam, []);
if (isset($counters[$key])) {
$value = $this->get($key, $defaultValue);
if ($delete) {
$this->removeFlash($key);
} elseif ($counters[$key] < 0) {
// mark for deletion in the next request
$counters[$key] = 1;
$_SESSION[$this->flashParam] = $counters;
}
return $value;
}
return $defaultValue;
}
Defined in: yii\web\Session::getGCProbability()
public float getGCProbability ( ) | ||
return | float |
The probability (percentage) that the GC (garbage collection) process is started on every session initialization. |
---|
public function getGCProbability()
{
return (float) (ini_get('session.gc_probability') / ini_get('session.gc_divisor') * 100);
}
Defined in: yii\web\Session::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. |
---|
public function getHasSessionId()
{
if ($this->_hasSessionId === null) {
$name = $this->getName();
$request = Yii::$app->getRequest();
if (!empty($_COOKIE[$name]) && ini_get('session.use_cookies')) {
$this->_hasSessionId = true;
} elseif (!ini_get('session.use_only_cookies') && ini_get('session.use_trans_sid')) {
$this->_hasSessionId = $request->get($name) != '';
} else {
$this->_hasSessionId = false;
}
}
return $this->_hasSessionId;
}
public string getId ( ) | ||
return | string |
The current session ID |
---|
public function getId()
{
return session_id();
}
Defined in: yii\web\Session::getIsActive()
public boolean getIsActive ( ) | ||
return | boolean |
Whether the session has started |
---|
public function getIsActive()
{
return session_status() === PHP_SESSION_ACTIVE;
}
Defined in: yii\web\Session::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. |
---|
#[\ReturnTypeWillChange]
public function getIterator()
{
$this->open();
return new SessionIterator();
}
Defined in: yii\web\Session::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 |
---|
public function getName()
{
return session_name();
}
Generates a query to get the session from db
protected yii\db\Query getReadQuery ( $id ) | ||
$id | string |
The id of the session |
protected function getReadQuery($id)
{
return (new Query())
->from($this->sessionTable)
->where('[[expire]]>:expire AND [[id]]=:id', [':expire' => time(), ':id' => $id]);
}
Defined in: yii\web\Session::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'. |
---|
public function getSavePath()
{
return session_save_path();
}
Defined in: yii\web\Session::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). |
---|
public function getTimeout()
{
return (int) ini_get('session.gc_maxlifetime');
}
Defined in: yii\web\Session::getUseCookies()
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. |
---|
public function getUseCookies()
{
if (ini_get('session.use_cookies') === '0') {
return false;
} elseif (ini_get('session.use_only_cookies') === '1') {
return true;
}
return null;
}
Defined in: yii\web\MultiFieldSession::getUseCustomStorage()
Returns a value indicating whether to use custom session storage.
This method overrides the parent implementation and always returns true.
public boolean getUseCustomStorage ( ) | ||
return | boolean |
Whether to use custom storage. |
---|
public function getUseCustomStorage()
{
return true;
}
public boolean getUseStrictMode ( ) | ||
return | boolean |
Whether strict mode is enabled or not. |
---|
public function getUseStrictMode()
{
if (PHP_VERSION_ID < 50502) {
return self::$_useStrictModePolyfill;
}
return (bool)ini_get('session.use_strict_mode');
}
Defined in: yii\web\Session::getUseTransparentSessionID()
public boolean getUseTransparentSessionID ( ) | ||
return | boolean |
Whether transparent sid support is enabled or not, defaults to false. |
---|
public function getUseTransparentSessionID()
{
return ini_get('session.use_trans_sid') == 1;
}
Defined in: yii\web\Session::has()
public boolean has ( $key ) | ||
$key | mixed |
Session variable name |
return | boolean |
Whether there is the named session variable |
---|
public function has($key)
{
$this->open();
return isset($_SESSION[$key]);
}
Defined in: yii\base\Component::hasEventHandlers()
Returns a value indicating whether there is any handler attached to the named event.
public boolean hasEventHandlers ( $name ) | ||
$name | string |
The event name |
return | boolean |
Whether there is any handler attached to the event. |
---|
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
Defined in: yii\web\Session::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 |
---|
public function hasFlash($key)
{
return $this->getFlash($key) !== null;
}
Defined in: yii\base\Component::hasMethod()
Returns a value indicating whether a method is defined.
A method is defined if:
- the class has a method with the specified name
- an attached behavior has a method with the given name (when
$checkBehaviors
is true).
public boolean hasMethod ( $name, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkBehaviors | boolean |
Whether to treat behaviors' methods as methods of this component |
return | boolean |
Whether the method is defined |
---|
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::hasProperty()
Returns a value indicating whether a property is defined for this component.
A property is defined if:
- the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a property of the given name (when
$checkBehaviors
is true).
See also:
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property is defined |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
Initializes the DbSession component.
This method will initialize the $db property to make sure it refers to a valid DB connection.
public void init ( ) | ||
throws | yii\base\InvalidConfigException |
if $db is invalid. |
---|
public function init()
{
parent::init();
$this->db = Instance::ensure($this->db, Connection::className());
}
Defined in: yii\base\Component::off()
Detaches an existing event handler from this component.
This method is the opposite of on().
Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.
See also on().
public boolean off ( $name, $handler = null ) | ||
$name | string |
Event name |
$handler | callable|null |
The event handler to be removed. If it is null, all handlers attached to the named event will be removed. |
return | boolean |
If a handler is found and detached |
---|
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
// plain event names
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
// wildcard event names
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
// remove empty wildcards to save future redundant regex checks:
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
Defined in: yii\web\Session::offsetExists()
This method is required by the interface ArrayAccess.
public boolean offsetExists ( $offset ) | ||
$offset | integer|string |
The offset to check on |
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
$this->open();
return isset($_SESSION[$offset]);
}
Defined in: yii\web\Session::offsetGet()
This method is required by the interface ArrayAccess.
public mixed offsetGet ( $offset ) | ||
$offset | integer|string |
The offset to retrieve element. |
return | mixed |
The element at the offset, null if no element is found at the offset |
---|
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
$this->open();
return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
}
Defined in: yii\web\Session::offsetSet()
This method is required by the interface ArrayAccess.
public void offsetSet ( $offset, $item ) | ||
$offset | integer|string |
The offset to set element |
$item | mixed |
The element value |
#[\ReturnTypeWillChange]
public function offsetSet($offset, $item)
{
$this->open();
$_SESSION[$offset] = $item;
}
Defined in: yii\web\Session::offsetUnset()
This method is required by the interface ArrayAccess.
public void offsetUnset ( $offset ) | ||
$offset | integer|string |
The offset to unset element |
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
$this->open();
unset($_SESSION[$offset]);
}
Defined in: yii\base\Component::on()
Attaches an event handler to an event.
The event handler must be a valid PHP callback. The following are some examples:
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
The event handler must be defined with the following signature,
function ($event)
where $event
is an yii\base\Event object which includes parameters associated with the event.
Since 2.0.14 you can specify event name as a wildcard pattern:
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
See also off().
public void on ( $name, $handler, $data = null, $append = true ) | ||
$name | string |
The event name |
$handler | callable |
The event handler |
$data | mixed |
The data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via yii\base\Event::$data. |
$append | boolean |
Whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list. |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
Defined in: yii\web\Session::open()
Starts the session.
public void open ( ) |
public function open()
{
if ($this->getIsActive()) {
return;
}
$this->registerSessionHandler();
$this->setCookieParamsInternal();
YII_DEBUG ? session_start() : @session_start();
if ($this->getUseStrictMode() && $this->_forceRegenerateId) {
$this->regenerateID();
$this->_forceRegenerateId = null;
}
if ($this->getIsActive()) {
Yii::info('Session started', __METHOD__);
$this->updateFlashCounters();
} else {
$error = error_get_last();
$message = isset($error['message']) ? $error['message'] : 'Failed to start session.';
Yii::error($message, __METHOD__);
}
}
Updates the current session ID with a newly generated one.
Please refer to https://www.php.net/session_regenerate_id for more details.
This method has no effect when session is not active. Make sure to call open() before calling it.
public void regenerateID ( $deleteOldSession = false ) | ||
$deleteOldSession | boolean |
Whether to delete the old associated session file or not. |
public function regenerateID($deleteOldSession = false)
{
$oldID = session_id();
// if no session is started, there is nothing to regenerate
if (empty($oldID)) {
return;
}
parent::regenerateID(false);
$newID = session_id();
// if session id regeneration failed, no need to create/update it.
if (empty($newID)) {
Yii::warning('Failed to generate new session ID', __METHOD__);
return;
}
$row = $this->db->useMaster(function () use ($oldID) {
return (new Query())->from($this->sessionTable)
->where(['id' => $oldID])
->createCommand($this->db)
->queryOne();
});
if ($row !== false && $this->getIsActive()) {
if ($deleteOldSession) {
$this->db->createCommand()
->update($this->sessionTable, ['id' => $newID], ['id' => $oldID])
->execute();
} else {
$row['id'] = $newID;
$this->db->createCommand()
->insert($this->sessionTable, $row)
->execute();
}
}
}
Defined in: yii\web\Session::registerSessionHandler()
Registers session handler.
protected void registerSessionHandler ( ) | ||
throws | yii\base\InvalidConfigException |
---|
protected function registerSessionHandler()
{
$sessionModuleName = session_module_name();
if (static::$_originalSessionModule === null) {
static::$_originalSessionModule = $sessionModuleName;
}
if ($this->handler !== null) {
if (!is_object($this->handler)) {
$this->handler = Yii::createObject($this->handler);
}
if (!$this->handler instanceof \SessionHandlerInterface) {
throw new InvalidConfigException('"' . get_class($this) . '::handler" must implement the SessionHandlerInterface.');
}
YII_DEBUG ? session_set_save_handler($this->handler, false) : @session_set_save_handler($this->handler, false);
} elseif ($this->getUseCustomStorage()) {
if (YII_DEBUG) {
session_set_save_handler(
[$this, 'openSession'],
[$this, 'closeSession'],
[$this, 'readSession'],
[$this, 'writeSession'],
[$this, 'destroySession'],
[$this, 'gcSession']
);
} else {
@session_set_save_handler(
[$this, 'openSession'],
[$this, 'closeSession'],
[$this, 'readSession'],
[$this, 'writeSession'],
[$this, 'destroySession'],
[$this, 'gcSession']
);
}
} elseif (
$sessionModuleName !== static::$_originalSessionModule
&& static::$_originalSessionModule !== null
&& static::$_originalSessionModule !== 'user'
) {
session_module_name(static::$_originalSessionModule);
}
}
Defined in: yii\web\Session::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. |
---|
public function remove($key)
{
$this->open();
if (isset($_SESSION[$key])) {
$value = $_SESSION[$key];
unset($_SESSION[$key]);
return $value;
}
return null;
}
Defined in: yii\web\Session::removeAll()
Removes all session variables.
public void removeAll ( ) |
public function removeAll()
{
$this->open();
foreach (array_keys($_SESSION) as $key) {
unset($_SESSION[$key]);
}
}
Defined in: yii\web\Session::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.
See also:
public void removeAllFlashes ( ) |
public function removeAllFlashes()
{
$counters = $this->get($this->flashParam, []);
foreach (array_keys($counters) as $key) {
unset($_SESSION[$key]);
}
unset($_SESSION[$this->flashParam]);
}
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. |
---|
public function removeFlash($key)
{
$counters = $this->get($this->flashParam, []);
$value = isset($_SESSION[$key], $counters[$key]) ? $_SESSION[$key] : null;
unset($counters[$key], $_SESSION[$key]);
$_SESSION[$this->flashParam] = $counters;
return $value;
}
Defined in: yii\web\Session::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 |
public function set($key, $value)
{
$this->open();
$_SESSION[$key] = $value;
}
Defined in: yii\web\Session::setCacheLimiter()
Set cache limiter
public void setCacheLimiter ( $cacheLimiter ) | ||
$cacheLimiter | string |
public function setCacheLimiter($cacheLimiter)
{
$this->freeze();
session_cache_limiter($cacheLimiter);
$this->unfreeze();
}
Defined in: yii\web\Session::setCookieParams()
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://www.php.net/manual/en/function.session-set-cookie-params.php.
public void setCookieParams ( array $value ) | ||
$value | array |
Cookie parameters, valid keys include:
]
|
throws | yii\base\InvalidArgumentException |
if the parameters are incomplete. |
---|
public function setCookieParams(array $value)
{
$this->_cookieParams = $value;
}
Defined in: yii\web\Session::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.
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. |
public function setFlash($key, $value = true, $removeAfterAccess = true)
{
$counters = $this->get($this->flashParam, []);
$counters[$key] = $removeAfterAccess ? -1 : 0;
$_SESSION[$key] = $value;
$_SESSION[$this->flashParam] = $counters;
}
Defined in: yii\web\Session::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. |
---|
public function setGCProbability($value)
{
$this->freeze();
if ($value >= 0 && $value <= 100) {
// percent * 21474837 / 2147483647 ≈ percent * 0.01
ini_set('session.gc_probability', floor($value * 21474836.47));
ini_set('session.gc_divisor', 2147483647);
} else {
throw new InvalidArgumentException('GCProbability must be a value between 0 and 100.');
}
$this->unfreeze();
}
Defined in: yii\web\Session::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. |
public function setHasSessionId($value)
{
$this->_hasSessionId = $value;
}
public void setId ( $value ) | ||
$value | string |
The session ID for the current session |
public function setId($value)
{
session_id($value);
}
Defined in: yii\web\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". |
public function setName($value)
{
$this->freeze();
session_name($value);
$this->unfreeze();
}
Defined in: yii\web\Session::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 |
---|
public function setSavePath($value)
{
$path = Yii::getAlias($value);
if (is_dir($path)) {
session_save_path($path);
} else {
throw new InvalidArgumentException("Session save path is not a valid directory: $value");
}
}
Defined in: yii\web\Session::setTimeout()
public void setTimeout ( $value ) | ||
$value | integer |
The number of seconds after which data will be seen as 'garbage' and cleaned up |
public function setTimeout($value)
{
$this->freeze();
ini_set('session.gc_maxlifetime', $value);
$this->unfreeze();
}
Defined in: yii\web\Session::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. |
public function setUseCookies($value)
{
$this->freeze();
if ($value === false) {
ini_set('session.use_cookies', '0');
ini_set('session.use_only_cookies', '0');
} elseif ($value === true) {
ini_set('session.use_cookies', '1');
ini_set('session.use_only_cookies', '1');
} else {
ini_set('session.use_cookies', '1');
ini_set('session.use_only_cookies', '0');
}
$this->unfreeze();
}
Defined in: yii\web\Session::setUseStrictMode()
See also https://www.php.net/manual/en/session.configuration.php#ini.session.use-strict-mode.
public void setUseStrictMode ( $value ) | ||
$value | boolean |
Whether strict mode is enabled or not.
When |
public function setUseStrictMode($value)
{
if (PHP_VERSION_ID < 50502) {
if ($this->getUseCustomStorage() || !$value) {
self::$_useStrictModePolyfill = $value;
} else {
throw new InvalidConfigException('Enabling `useStrictMode` on PHP < 5.5.2 is only supported with custom storage classes.');
}
} else {
$this->freeze();
ini_set('session.use_strict_mode', $value ? '1' : '0');
$this->unfreeze();
}
}
Defined in: yii\web\Session::setUseTransparentSessionID()
public void setUseTransparentSessionID ( $value ) | ||
$value | boolean |
Whether transparent sid support is enabled or not. |
public function setUseTransparentSessionID($value)
{
$this->freeze();
ini_set('session.use_trans_sid', $value ? '1' : '0');
$this->unfreeze();
}
Defined in: yii\base\Component::trigger()
Triggers an event.
This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.
public void trigger ( $name, yii\base\Event $event = null ) | ||
$name | string |
The event name |
$event | yii\base\Event|null |
The event instance. If not set, a default yii\base\Event object will be created. |
public function trigger($name, Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
// stop further handling if the event is handled
if ($event->handled) {
return;
}
}
}
// invoke class-level attached handlers
Event::trigger($this, $name, $event);
}
Method typecasts $fields before passing them to PDO.
Default implementation casts field data
to \PDO::PARAM_LOB
.
You can override this method in case you need special type casting.
protected array typecastFields ( $fields ) | ||
$fields | array |
Fields, that will be passed to PDO. Key - name, Value - value |
protected function typecastFields($fields)
{
if (isset($fields['data']) && !is_array($fields['data']) && !is_object($fields['data'])) {
$fields['data'] = new PdoValue($fields['data'], \PDO::PARAM_LOB);
}
return $fields;
}
Defined in: yii\web\Session::unfreeze()
Starts session and restores data from temporary variable
protected void unfreeze ( ) |
protected function unfreeze()
{
if (null !== $this->_frozenSessionData) {
YII_DEBUG ? session_start() : @session_start();
if ($this->getIsActive()) {
Yii::info('Session unfrozen', __METHOD__);
} else {
$error = error_get_last();
$message = isset($error['message']) ? $error['message'] : 'Failed to unfreeze session.';
Yii::error($message, __METHOD__);
}
$_SESSION = $this->_frozenSessionData;
$this->_frozenSessionData = null;
}
}
Defined in: yii\web\Session::updateFlashCounters()
Updates the counters for flash messages and removes outdated flash messages.
This method should only be called once in init().
protected void updateFlashCounters ( ) |
protected function updateFlashCounters()
{
$counters = $this->get($this->flashParam, []);
if (is_array($counters)) {
foreach ($counters as $key => $count) {
if ($count > 0) {
unset($counters[$key], $_SESSION[$key]);
} elseif ($count == 0) {
$counters[$key]++;
}
}
$_SESSION[$this->flashParam] = $counters;
} else {
// fix the unexpected problem that flashParam doesn't return an array
unset($_SESSION[$this->flashParam]);
}
}
Signup or Login in order to comment.