Skip to content

Session ​

Type
Class
Namespace
craft\web
Inherits
craft\web\Session » yii\web\Session » yii\base\Component » yii\base\BaseObject
Implements
ArrayAccess, Countable, IteratorAggregate, yii\base\Configurable
Since
3.0.0

Extends yii\web\Session to add support for setting the session folder and creating it if it doesn’t exist.

View source

Public Properties ​

PropertyDescription
allFlashesarray – Flash messages (key => message or key => [message1, message2]).
behaviorsyii\base\Behavior – List of behaviors attached to this component.
cacheLimiterstring – Current cache limiter.
cookieParamsarray – The session cookie parameters.
countinteger – The number of session variables.
flashstring – The key identifying the flash message.
flashParamstring – The name of the session variable that stores the flash message data.
gCProbabilityfloat – The probability (percentage) that the GC (garbage collection) process is started on every session initialization.
handlerSessionHandlerInterface, array – An object implementing the SessionHandlerInterface or a configuration array.
hasSessionIdboolean – Whether the current request has sent the session ID.
idstring – The current session ID.
isActiveboolean – Whether the session has started.
iteratoryii\web\SessionIterator – An iterator for traversing the session variables.
namestring – The current session name.
savePathstring – The current session save path, defaults to '/tmp'.
timeoutinteger – The number of seconds after which data will be seen as 'garbage' and cleaned up.
useCookiesboolean, null – The value indicating whether cookies should be used to store session IDs.
useCustomStorageboolean – Whether to use custom storage.
useStrictModeboolean – Whether strict mode is enabled or not.
useTransparentSessionIDboolean – Whether transparent sid support is enabled or not, defaults to false.

Protected Properties ​

PropertyDescription
_forceRegenerateIdstring, null – Holds the session id in case useStrictMode is enabled and the session id needs to be regenerated
_originalSessionModulestring, 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.

Public Methods ​

MethodDescription
__call()Calls the named method which is not a class method.
__clone()This method is called after the object is created by cloning an existing one.
__construct()Constructor.
__get()Returns the value of a component property.
__isset()Checks if a property is set, i.e. defined and not null.
__set()Sets the value of a component property.
__unset()Sets a component property to be null.
addFlash()Adds a flash message.
attachBehavior()Attaches a behavior to this component.
attachBehaviors()Attaches a list of behaviors to the component.
behaviors()Returns a list of behaviors that this component should behave as.
canGetProperty()Returns a value indicating whether a property can be read.
canSetProperty()Returns a value indicating whether a property can be set.
className()Returns the fully qualified name of this class.
close()Ends the current session and store session data.
count()Returns the number of items in the session.
destroy()Frees all session variables and destroys all data registered to a session.
detachBehavior()Detaches a behavior from the component.
detachBehaviors()Detaches all behaviors from the component.
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.
get()Returns the session variable value with the session variable name.
getAllFlashes()Returns all flash messages.
getBehavior()Returns the named behavior object.
getBehaviors()Returns all behaviors attached to this component.
getCacheLimiter()Returns current cache limiter
getCookieParams()
getCount()Returns the number of items in the session.
getFlash()Returns a flash message.
getGCProbability()
getHasSessionId()Returns a value indicating whether the current request has sent the session ID.
getId()Gets the session ID.
getIsActive()
getIterator()Returns an iterator for traversing the session variables.
getName()Gets the name of the current session.
getSavePath()Gets the current session save path.
getTimeout()
getUseCookies()Returns the value indicating whether cookies should be used to store session IDs.
getUseCustomStorage()Returns a value indicating whether to use custom session storage.
getUseStrictMode()
getUseTransparentSessionID()
has()
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.
hasFlash()Returns a value indicating whether there are flash messages associated with the specified key.
hasMethod()Returns a value indicating whether a method is defined.
hasProperty()Returns a value indicating whether a property is defined for this component.
init()Initializes the application component.
off()Detaches an existing event handler from this component.
offsetExists()This method is required by the interface ArrayAccess.
offsetGet()This method is required by the interface ArrayAccess.
offsetSet()This method is required by the interface ArrayAccess.
offsetUnset()This method is required by the interface ArrayAccess.
on()Attaches an event handler to an event.
open()Starts the session.
regenerateID()Updates the current session ID with a newly generated one.
remove()Removes a session variable.
removeAll()Removes all session variables.
removeAllFlashes()Removes all flash messages.
removeFlash()Removes a flash message.
set()Adds a session variable.
setCacheLimiter()Set cache limiter
setCookieParams()Sets the session cookie parameters.
setFlash()Sets a flash message.
setGCProbability()
setHasSessionId()Sets the value indicating whether the current request has sent the session ID.
setId()Sets the session ID.
setName()Sets the name for the current session.
setSavePath()Sets the current session save path.
setTimeout()
setUseCookies()Sets the value indicating whether cookies should be used to store session IDs.
setUseStrictMode()
setUseTransparentSessionID()
trigger()Triggers an event.

getAllFlashes() ​

Returns all flash messages.

You may use this method to display all the flash messages in a view file:

php
<?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.

View source

Arguments ​

  • $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.

Returns ​

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


Example ​

php
$messages = Craft::$app->session->getAllFlashes(true);
twig
{% set messages = craft.app.session.getAllFlashes(true) %}
{% for key, message in messages %}
  <p class="{{ key }}">
    {{ message }}
  </p>
{% endfor %}

getFlash() ​

Returns a flash message.

View source

Arguments ​

  • $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.

Returns ​

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


Example ​

php
$message = Craft::$app->session->getFlash('notice', null, true);
twig
{% set message = craft.app.session.getFlash('notice', null, true) %}
{% if message %}
  <p class="notice">
    {{ message }}
  </p>
{% endif %}

hasFlash() ​

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

View source

Arguments ​

  • $key (string) – Key identifying the flash message type

Returns ​

boolean – Whether any flash messages exist under specified key


Example ​

php
$hasNotice = Craft::$app->session->hasFlash('notice');
twig
{% if craft.app.session.hasFlash('notice') %}
  <p class="notice">
    {{ craft.app.session.getFlash('notice', null, true) }}
  </p>
{% endif %}

Protected Methods ​

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