Skip to content
PHP Ecosystem
Explore

DbSession

API reference › yii › web › DbSession

DbSession extends 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 MultiFieldSession, thus it allows saving extra fields into the $sessionTable. Refer to MultiFieldSession for more details.

PropertyTypeDescriptionDefined by
$allFlashes read-onlyarrayFlash messages (key => message or key => [message1, message2]).Session
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$cacheLimiterstringCurrent cache limiter.Session
$cookieParamsarrayThe session cookie parameters.Session
$count read-onlyintThe number of session variables.Session
$dbyii\db\Connection|array|stringThe DB connection object or the application component ID of the DB connection. Default: 'db'.DbSession
$flash write-onlystringThe key identifying the flash message.Session
$flashParamstringThe name of the session variable that stores the flash message data. Default: '__flash'.Session
$gCProbabilityfloatThe probability (percentage) that the GC (garbage collection) process is started on every session initialization.Session
$handlerSessionHandlerInterface|arrayAn object implementing the SessionHandlerInterface or a configuration array. Default: null.Session
$hasSessionIdboolWhether the current request has sent the session ID.Session
$idstringThe current session ID.Session
$isActive read-onlyboolWhether the session has started.Session
$iterator read-onlySessionIteratorAn iterator for traversing the session variables.Session
$namestringThe current session name.Session
$readCallbackcallableA callback that will be called during session data reading. Default: null.MultiFieldSession
$savePathstringThe current session save path, defaults to ‘/tmp’.Session
$sessionTablestringThe name of the DB table that stores the session data. Default: '{{%session}}'.DbSession
$timeoutintThe number of seconds after which data will be seen as ‘garbage’ and cleaned up.Session
$useCookiesbool|nullThe value indicating whether cookies should be used to store session IDs.Session
$useCustomStorage read-onlyboolWhether to use custom storage.MultiFieldSession
$useStrictModeboolWhether strict mode is enabled or not.Session
$useTransparentSessionIDboolWhether transparent sid support is enabled or not, defaults to false.Session
$writeCallbackcallable|nullA callback that will be called during session data writing. Default: null.MultiFieldSession
$_forceRegenerateId protectedstring|nullHolds the session id in case useStrictMode is enabled and the session id needs to be regenerated Default: null.Session
$_originalSessionModule protected staticstring|nullHolds 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. Default: null.Session
$fields protectedarraySession fields to be written into session table columns Default: []. Available since 2.0.17.DbSession
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__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
__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.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() staticReturns the fully qualified name of this class.yii\base\BaseObject
close()Ends the current session and store session data.DbSession
count()Returns the number of items in the session.Session
destroy()Frees all session variables and destroys all data registered to a session.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.Session
getAllFlashes()Returns all flash messages.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 limiterSession
getCookieParams()Session
getCount()Returns the number of items in the session.Session
getFlash()Returns a flash message.Session
getGCProbability()Session
getHasSessionId()Returns a value indicating whether the current request has sent the session ID.Session
getId()Gets the session ID.Session
getIsActive()Session
getIterator()Returns an iterator for traversing the session variables.Session
getName()Gets the name of the current session.Session
getSavePath()Gets the current session save path.Session
getTimeout()Session
getUseCookies()Returns the value indicating whether cookies should be used to store session IDs.Session
getUseCustomStorage()Returns a value indicating whether to use custom session storage.MultiFieldSession
getUseStrictMode()Session
getUseTransparentSessionID()Session
has()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.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.DbSession
off()Detaches an existing event handler from this component.yii\base\Component
offsetExists()This method is required by the interface ArrayAccess.Session
offsetGet()This method is required by the interface ArrayAccess.Session
offsetSet()This method is required by the interface ArrayAccess.Session
offsetUnset()This method is required by the interface ArrayAccess.Session
on()Attaches an event handler to an event.yii\base\Component
open()Starts the session.Session
regenerateID()Updates the current session ID with a newly generated one.DbSession
remove()Removes a session variable.Session
removeAll()Removes all session variables.Session
removeAllFlashes()Removes all flash messages.Session
removeFlash()Removes a flash message.Session
set()Adds a session variable.Session
setCacheLimiter()Set cache limiterSession
setCookieParams()Sets the session cookie parameters.Session
setFlash()Sets a flash message.Session
setGCProbability()Session
setHasSessionId()Sets the value indicating whether the current request has sent the session ID.Session
setId()Sets the session ID.Session
setName()Sets the name for the current session.Session
setSavePath()Sets the current session save path.Session
setTimeout()Session
setUseCookies()Sets the value indicating whether cookies should be used to store session IDs.Session
setUseStrictMode()Session
setUseTransparentSessionID()Session
trigger()Triggers an event.yii\base\Component
composeFields() protectedComposes storage field set for session writing.MultiFieldSession
extractData() protectedExtracts session data from storage field set.MultiFieldSession
freeze() protectedIf session is started it’s not possible to edit session ini settings. In PHP7.2+ it throws exception.Session
getReadQuery() protectedGenerates a query to get the session from dbDbSession
registerSessionHandler() protectedRegisters session handler.Session
typecastFields() protectedTypecasts $fields before passing them to PDO.DbSession
unfreeze() protectedStarts session and restores data from temporary variableSession
updateFlashCounters() protectedUpdates the counters for flash messages and removes outdated flash messages.Session
public yii\db\Connection|array|string $db = 'db'

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.

public string $sessionTable = '{{%session}}'

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.

public function close(): mixed

Ends the current session and store session data.

Returns

mixed

Since

2.0.17

public function init(): mixed

Initializes the DbSession component.

This method will initialize the $db property to make sure it refers to a valid DB connection.

Returns

mixed

Throws

public function regenerateID(mixed $deleteOldSession = false): mixed

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.

Parameters

ParameterTypeDescription
$deleteOldSessionmixedWhether to delete the old associated session file or not.

Returns

mixed

protected function getReadQuery(string $id): yii\db\Query

Generates a query to get the session from db

Parameters

ParameterTypeDescription
$idstringThe id of the session

Returns

yii\db\Query

protected function typecastFields(array $fields): array

Typecasts $fields before passing them to PDO.

Applies the data column type cast resolved from the session table schema, so binary payloads bind correctly across drivers (for example, MSSQL varbinary, which requires a CONVERT to avoid implicit conversion errors).

Override this method when special type casting is required.

Parameters

ParameterTypeDescription
$fieldsarrayFields passed to PDO, keyed by column name.

Returns

array: Fields with the data value cast for the active driver.

Since

2.0.13