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',
]
DbSession extends yii\web\MultiFieldSession, thus it allows saving extra fields into the $sessionTable. Refer to yii\web\MultiFieldSession for more 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 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 function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
Defined in: yii\base\BaseObject::__construct()
Constructor.
The default implementation does two things:
$config
.If this method is overridden in a child class, it is recommended that
$config
here.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:
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 function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter();
}
$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:
false
for non existing propertiesDo not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($component->property)
.
See also https://www.php.net/manual/en/function.isset.php.
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
$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:
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 function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
$name = trim(substr($name, 3));
if ($value instanceof Behavior) {
$this->attachBehavior($name, $value);
} elseif ($value instanceof \Closure) {
$this->attachBehavior($name, call_user_func($value));
} elseif (isset($value['__class']) && is_subclass_of($value['__class'], Behavior::class)) {
$this->attachBehavior($name, Yii::createObject($value));
} elseif (!isset($value['__class']) && isset($value['class']) && is_subclass_of($value['class'], Behavior::class)) {
$this->attachBehavior($name, Yii::createObject($value));
} elseif (is_string($value) && is_subclass_of($value, Behavior::class, true)) {
$this->attachBehavior($name, Yii::createObject($value));
} else {
throw new InvalidConfigException('Class is not of type ' . Behavior::class . ' or its subclasses');
}
return;
}
$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:
Do not call this method directly as it is a PHP magic method that will be implicitly called when executing unset($component->property)
.
See also https://www.php.net/manual/en/function.unset.php.
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
$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);
}
public void addFlash ( $key, $value = true, $removeAfterAccess = true ) $key string
The key identifying the flash message.
$value mixedFlash message
$removeAfterAccess booleanWhether 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];
}
}
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
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 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:
$checkVars
is true);$checkBehaviors
is true).See also canSetProperty().
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) $name stringThe property name
$checkVars booleanWhether to treat member variables as properties
$checkBehaviors booleanWhether to treat behaviors' properties as properties of this component
return booleanWhether 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:
$checkVars
is true);$checkBehaviors
is true).See also canGetProperty().
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) $name stringThe property name
$checkVars booleanWhether to treat member variables as properties
$checkBehaviors booleanWhether to treat behaviors' properties as properties of this component
return booleanWhether 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;
}
Deprecated since 2.0.14. On PHP >=5.5, use ::class
instead.
public static function className()
{
return get_called_class();
}
Ends the current session and store session data.
public function close()
{
if ($this->getIsActive()) {
$this->fields = $this->composeFields();
YII_DEBUG ? session_write_close() : @session_write_close();
}
}
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;
}
public function count()
{
return $this->getCount();
}
public function destroy()
{
if ($this->getIsActive()) {
$sessionId = session_id();
$this->close();
$this->setId($sessionId);
$this->open();
session_unset();
session_destroy();
$this->setId($sessionId);
}
}
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;
}
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
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 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.
The session variable name
$defaultValue mixedThe default value to be returned when the session variable does not exist.
return mixedThe 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 booleanWhether 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 arrayFlash 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) {
$counters[$key] = 1;
}
} else {
unset($counters[$key]);
}
}
$_SESSION[$this->flashParam] = $counters;
return $flashes;
}
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
public function getCacheLimiter()
{
return session_cache_limiter();
}
public function getCookieParams()
{
return array_merge(session_get_cookie_params(), array_change_key_case($this->_cookieParams));
}
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 mixedValue to be returned if the flash message does not exist.
$delete booleanWhether 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 mixedThe 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) {
$counters[$key] = 1;
$_SESSION[$this->flashParam] = $counters;
}
return $value;
}
return $defaultValue;
}
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 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 function getId()
{
return session_id();
}
public function getIsActive()
{
return session_status() === PHP_SESSION_ACTIVE;
}
public function getIterator()
{
$this->open();
return new SessionIterator();
}
public function getName()
{
return session_name();
}
Generates a query to get the session from db
protected function getReadQuery($id)
{
return (new Query())
->from($this->sessionTable)
->where('[[expire]]>:expire AND [[id]]=:id', [':expire' => time(), ':id' => $id]);
}
public function getSavePath()
{
return session_save_path();
}
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');
}
public function getUseCookies()
{
if (ini_get('session.use_cookies') === '0') {
return false;
} elseif (ini_get('session.use_only_cookies') === '1') {
return true;
}
return null;
}
public function getUseCustomStorage()
{
return true;
}
public function getUseStrictMode()
{
if (PHP_VERSION_ID < 50502) {
return self::$_useStrictModePolyfill;
}
return (bool)ini_get('session.use_strict_mode');
}
public function getUseTransparentSessionID()
{
return ini_get('session.use_trans_sid') == 1;
}
public boolean has ( $key ) $key mixed
Session variable name
return booleanWhether there is the named session variable
public function has($key)
{
$this->open();
return isset($_SESSION[$key]);
}
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);
}
public boolean hasFlash ( $key ) $key string
Key identifying the flash message type
return booleanWhether 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:
$checkBehaviors
is true).The property name
$checkBehaviors booleanWhether to treat behaviors' methods as methods of this component
return booleanWhether 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:
$checkVars
is true);$checkBehaviors
is true).See also:
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) $name stringThe property name
$checkVars booleanWhether to treat member variables as properties
$checkBehaviors booleanWhether to treat behaviors' properties as properties of this component
return booleanWhether 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 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 stringEvent name
$handler callable|nullThe event handler to be removed. If it is null, all handlers attached to the named event will be removed.
return booleanIf 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;
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;
}
}
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]);
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
public function offsetExists($offset)
{
$this->open();
return isset($_SESSION[$offset]);
}
public mixed offsetGet ( $offset ) $offset integer|string
The offset to retrieve element.
return mixedThe element at the offset, null if no element is found at the offset
public function offsetGet($offset)
{
$this->open();
return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
}
public void offsetSet ( $offset, $item ) $offset integer|string
The offset to set element
$item mixedThe element value
public function offsetSet($offset, $item)
{
$this->open();
$_SESSION[$offset] = $item;
}
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) { ... }
[$object, 'handleClick']
['Page', 'handleClick']
'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 stringThe event name
$handler callableThe event handler
$data mixedThe 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 booleanWhether 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]);
}
}
public function open()
{
if ($this->getIsActive()) {
return;
}
$this->registerSessionHandler();
if ($this->getUseCookies() !== false) {
$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__);
}
}
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 (empty($oldID)) {
return;
}
parent::regenerateID(false);
$newID = session_id();
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();
}
}
}
protected function registerSessionHandler()
{
$sessionModuleName = session_module_name();
if (static::$_originalSessionModule === null) {
static::$_originalSessionModule = $sessionModuleName;
}
if ($this->handler === null && $this->getUseCustomStorage()) {
$this->handler = Yii::createObject(
[
'__class' => SessionHandler::class,
'__construct()' => [$this],
]
);
}
if ($this->handler !== null) {
if (is_array($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 (
$sessionModuleName !== static::$_originalSessionModule
&& static::$_originalSessionModule !== null
&& static::$_originalSessionModule !== 'user'
) {
session_module_name(static::$_originalSessionModule);
}
}
public mixed remove ( $key ) $key string
The name of the session variable to be removed
return mixedThe 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;
}
public function removeAll()
{
$this->open();
foreach (array_keys($_SESSION) as $key) {
unset($_SESSION[$key]);
}
}
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 mixedThe 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 stringSession variable name
$value mixedSession variable value
public function set($key, $value)
{
$this->open();
$_SESSION[$key] = $value;
}
public function setCacheLimiter($cacheLimiter)
{
$this->freeze();
session_cache_limiter($cacheLimiter);
$this->unfreeze();
}
public void setCookieParams ( array $value ) $value array
Cookie parameters, valid keys include: lifetime
, path
, domain
, secure
and httponly
. Starting with Yii 2.0.21 sameSite
is also supported. It requires PHP version 7.3.0 or higher. For security, an exception will be thrown if sameSite
is set while using an unsupported version of PHP. To use this feature across different PHP versions check the version first. E.g. `
php [
'sameSite' => PHP_VERSION_ID >= 70300 ? yii\web\Cookie::SAME_SITE_LAX : null,
] `
See https://owasp.org/www-community/SameSite for more information about sameSite
.
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 stringThe 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 mixedFlash message
$removeAfterAccess booleanWhether 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;
}
public function setGCProbability($value)
{
$this->freeze();
if ($value >= 0 && $value <= 100) {
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 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);
}
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();
}
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");
}
}
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:
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();
}
public void setUseStrictMode ( $value ) $value boolean
Whether strict mode is enabled or not. When true
this setting prevents the session component to use an uninitialized session ID. Note: Enabling useStrictMode
on PHP < 5.5.2 is only supported with custom storage classes. Warning! Although enabling strict mode is mandatory for secure sessions, the default value of 'session.use-strict-mode' is 0
.
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();
}
}
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 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);
if ($event->handled) {
return;
}
}
}
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 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;
}
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;
}
}
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 {
unset($_SESSION[$this->flashParam]);
}
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4