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.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$allFlashes read-only | array | Flash messages (key => message or key => [message1, message2]). | Session |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$cacheLimiter | string | Current cache limiter. | Session |
$cookieParams | array | The session cookie parameters. | Session |
$count read-only | int | The number of session variables. | Session |
$db | yii\| | The DB connection object or the application component ID of the DB connection. Default: 'db'. | DbSession |
$flash write-only | string | The key identifying the flash message. | Session |
$flashParam | string | The name of the session variable that stores the flash message data. Default: '__flash'. | Session |
$gCProbability | float | The probability (percentage) that the GC (garbage collection) process is started on every session initialization. | Session |
$handler | SessionHandlerInterface| | An object implementing the SessionHandlerInterface or a configuration array. Default: null. | Session |
$hasSessionId | bool | Whether the current request has sent the session ID. | Session |
$id | string | The current session ID. | Session |
$isActive read-only | bool | Whether the session has started. | Session |
$iterator read-only | SessionIterator | An iterator for traversing the session variables. | Session |
$name | string | The current session name. | Session |
$readCallback | callable | A callback that will be called during session data reading. Default: null. | MultiFieldSession |
$savePath | string | The current session save path, defaults to ‘/tmp’. | Session |
$sessionTable | string | The name of the DB table that stores the session data. Default: '{{%session}}'. | DbSession |
$timeout | int | The number of seconds after which data will be seen as ‘garbage’ and cleaned up. | Session |
$useCookies | bool| | The value indicating whether cookies should be used to store session IDs. | Session |
$useCustomStorage read-only | bool | Whether to use custom storage. | MultiFieldSession |
$useStrictMode | bool | Whether strict mode is enabled or not. | Session |
$useTransparentSessionID | bool | Whether transparent sid support is enabled or not, defaults to false. | Session |
$writeCallback | callable| | A callback that will be called during session data writing. Default: null. | MultiFieldSession |
$_forceRegenerateId protected | string| | Holds the session id in case useStrictMode is enabled and the session id needs to be regenerated Default: null. | Session |
$_originalSessionModule protected static | string| | 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. Default: null. | Session |
$fields protected | array | Session fields to be written into session table columns Default: []. Available since 2.0.17. | DbSession |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
addFlash() | Adds a flash message. | Session |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
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\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
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\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
getCacheLimiter() | Returns current cache limiter | Session |
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\ |
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\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
init() | Initializes the DbSession component. | DbSession |
off() | Detaches an existing event handler from this component. | yii\ |
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\ |
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 limiter | Session |
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\ |
composeFields() protected | Composes storage field set for session writing. | MultiFieldSession |
extractData() protected | Extracts session data from storage field set. | MultiFieldSession |
freeze() protected | If session is started it’s not possible to edit session ini settings. In PHP7.2+ it throws exception. | Session |
getReadQuery() protected | Generates a query to get the session from db | DbSession |
registerSessionHandler() protected | Registers session handler. | Session |
typecastFields() protected | Typecasts $fields before passing them to PDO. | DbSession |
unfreeze() protected | Starts session and restores data from temporary variable | Session |
updateFlashCounters() protected | Updates the counters for flash messages and removes outdated flash messages. | Session |
Property details
Section titled “Property details”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.
$sessionTable
Section titled “$sessionTable ”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.
Method details
Section titled “Method details”close()
Section titled “close() ”public function close(): mixedEnds the current session and store session data.
Returns
mixed
Since
2.0.17
init()
Section titled “init() ”public function init(): mixedInitializes the DbSession component.
This method will initialize the $db property to make sure it refers to a valid DB connection.
regenerateID()
Section titled “regenerateID() ”public function regenerateID(mixed $deleteOldSession = false): mixedUpdates 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
| Parameter | Type | Description |
|---|---|---|
$deleteOldSession | mixed | Whether to delete the old associated session file or not. |
Returns
mixed
getReadQuery()
Section titled “getReadQuery() ”protected function getReadQuery(string $id): yii\db\QueryGenerates a query to get the session from db
typecastFields()
Section titled “typecastFields() ”protected function typecastFields(array $fields): arrayTypecasts $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
| Parameter | Type | Description |
|---|---|---|
$fields | array | Fields passed to PDO, keyed by column name. |
Returns
array: Fields with the data value cast for the active driver.
Since
2.0.13