Package | system.web |
---|---|
Inheritance | class CDbHttpSession » CHttpSession » CApplicationComponent » CComponent |
Implements | Traversable, Countable, ArrayAccess, IteratorAggregate, IApplicationComponent |
Since | 1.0 |
Source Code | framework/web/CDbHttpSession.php |
CREATE TABLE YiiSession ( id CHAR(32) PRIMARY KEY, expire INTEGER, data BLOB )Where 'BLOB' refers to the BLOB-type of your preffered database.
Property | Type | Description | Defined By |
---|---|---|---|
autoCreateSessionTable | boolean | whether the session DB table should be automatically created if not exists. | CDbHttpSession |
autoStart | boolean | whether the session should be automatically started when the session application component is initialized, defaults to true. | CHttpSession |
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent |
connectionID | string | the ID of a CDbConnection application component. | CDbHttpSession |
cookieMode | string | how to use cookie to store session ID. | CHttpSession |
cookieParams | array | the session cookie parameters. | CHttpSession |
count | integer | Returns the number of items in the session. | CHttpSession |
gCProbability | float | the probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance. | CHttpSession |
isInitialized | boolean | Checks if this application component has been initialized. | CApplicationComponent |
isStarted | boolean | whether the session has started | CHttpSession |
iterator | CHttpSessionIterator | Returns an iterator for traversing the session variables. | CHttpSession |
keys | array | the list of session variable names | CHttpSession |
savePath | string | the current session save path, defaults to {@link https://php. | CHttpSession |
sessionID | string | the current session ID | CHttpSession |
sessionName | string | the current session name | CHttpSession |
sessionTableName | string | the name of the DB table to store session content. | CDbHttpSession |
timeout | integer | the number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds. | CHttpSession |
useCustomStorage | boolean | Returns a value indicating whether to use custom session storage. | CDbHttpSession |
useTransparentSessionID | boolean | whether transparent sid support is enabled or not, defaults to false. | CHttpSession |
Property | Type | Description | Defined By |
---|---|---|---|
dbConnection | CDbConnection | the DB connection instance | CDbHttpSession |
Method | Description | Defined By |
---|---|---|
__call() | Calls the named method which is not a class method. | CComponent |
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent |
__isset() | Checks if a property value is null. | CComponent |
__set() | Sets value of a component property. | CComponent |
__unset() | Sets a component property to be null. | CComponent |
add() | Adds a session variable. | CHttpSession |
asa() | Returns the named behavior object. | CComponent |
attachBehavior() | Attaches a behavior to this component. | CComponent |
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent |
attachEventHandler() | Attaches an event handler to an event. | CComponent |
canGetProperty() | Determines whether a property can be read. | CComponent |
canSetProperty() | Determines whether a property can be set. | CComponent |
clear() | Removes all session variables | CHttpSession |
close() | Ends the current session and store session data. | CHttpSession |
closeSession() | Session close handler. | CHttpSession |
contains() | CHttpSession | |
count() | Returns the number of items in the session. | CHttpSession |
destroy() | Frees all session variables and destroys all data registered to a session. | CHttpSession |
destroySession() | Session destroy handler. | CDbHttpSession |
detachBehavior() | Detaches a behavior from the component. | CComponent |
detachBehaviors() | Detaches all behaviors from the component. | CComponent |
detachEventHandler() | Detaches an existing event handler. | CComponent |
disableBehavior() | Disables an attached behavior. | CComponent |
disableBehaviors() | Disables all behaviors attached to this component. | CComponent |
enableBehavior() | Enables an attached behavior. | CComponent |
enableBehaviors() | Enables all behaviors attached to this component. | CComponent |
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent |
gcSession() | Session GC (garbage collection) handler. | CDbHttpSession |
get() | Returns the session variable value with the session variable name. | CHttpSession |
getCookieMode() | Returns how to use cookie to store session ID. Defaults to 'Allow'. | CHttpSession |
getCookieParams() | Returns the session cookie parameters. | CHttpSession |
getCount() | Returns the number of items in the session. | CHttpSession |
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent |
getGCProbability() | Returns the probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance. | CHttpSession |
getIsInitialized() | Checks if this application component has been initialized. | CApplicationComponent |
getIsStarted() | Checks whether the session has started | CHttpSession |
getIterator() | Returns an iterator for traversing the session variables. | CHttpSession |
getKeys() | Returns the list of session variable names | CHttpSession |
getSavePath() | Returns the current session save path, defaults to https://php.net/session.save_path. | CHttpSession |
getSessionID() | Returns the current session ID | CHttpSession |
getSessionName() | Returns the current session name | CHttpSession |
getTimeout() | Returns the number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds. | CHttpSession |
getUseCustomStorage() | Returns a value indicating whether to use custom session storage. | CDbHttpSession |
getUseTransparentSessionID() | Returns whether transparent sid support is enabled or not, defaults to false. | CHttpSession |
hasEvent() | Determines whether an event is defined. | CComponent |
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent |
hasProperty() | Determines whether a property is defined. | CComponent |
init() | Initializes the application component. | CHttpSession |
itemAt() | Returns the session variable value with the session variable name. | CHttpSession |
offsetExists() | This method is required by the interface ArrayAccess. | CHttpSession |
offsetGet() | This method is required by the interface ArrayAccess. | CHttpSession |
offsetSet() | This method is required by the interface ArrayAccess. | CHttpSession |
offsetUnset() | This method is required by the interface ArrayAccess. | CHttpSession |
open() | Starts the session if it has not started yet. | CHttpSession |
openSession() | Session open handler. | CDbHttpSession |
raiseEvent() | Raises an event. | CComponent |
readSession() | Session read handler. | CDbHttpSession |
regenerateID() | Updates the current session id with a newly generated one. | CDbHttpSession |
remove() | Removes a session variable. | CHttpSession |
setCacheLimiter() | Set cache limiter | CHttpSession |
setCookieMode() | Sets how to use cookie to store session ID. Valid values include 'none', 'allow' and 'only'. | CHttpSession |
setCookieParams() | Sets the session cookie parameters. | CHttpSession |
setGCProbability() | Sets the probability (percentage) that the gc (garbage collection) process is started on every session initialization. | CHttpSession |
setSavePath() | Sets the current session save path | CHttpSession |
setSessionID() | Sets the session ID for the current session | CHttpSession |
setSessionName() | Sets the session name for the current session, must be an alphanumeric string, defaults to PHPSESSID | CHttpSession |
setTimeout() | Sets the number of seconds after which data will be seen as 'garbage' and cleaned up | CHttpSession |
setUseTransparentSessionID() | Sets whether transparent sid support is enabled or not. | CHttpSession |
toArray() | CHttpSession | |
writeSession() | Session write handler. | CDbHttpSession |
Method | Description | Defined By |
---|---|---|
createSessionTable() | Creates the session DB table. | CDbHttpSession |
freeze() | If session is started we cannot edit session ini settings. | CHttpSession |
getDbConnection() | Returns the DB connection instance | CDbHttpSession |
unfreeze() | Start session and restore data from temporary variable | CHttpSession |
whether the session DB table should be automatically created if not exists. Defaults to true.
the ID of a CDbConnection application component. If not set, a SQLite database
will be automatically created and used. The SQLite database file is
is protected/runtime/session-YiiVersion.db
.
the DB connection instance
the name of the DB table to store session content. Note, if autoCreateSessionTable is false and you want to create the DB table manually by yourself, you need to make sure the DB table is of the following structure:
(id CHAR(32) PRIMARY KEY, expire INTEGER, data BLOB)
Returns a value indicating whether to use custom session storage. This method overrides the parent implementation and always returns true.
protected void createSessionTable(CDbConnection $db, string $tableName)
| ||
$db | CDbConnection | the database connection |
$tableName | string | the name of the table to be created |
protected function createSessionTable($db,$tableName)
{
switch($db->getDriverName())
{
case 'mysql':
$blob='LONGBLOB';
break;
case 'pgsql':
$blob='BYTEA';
break;
case 'sqlsrv':
case 'mssql':
case 'dblib':
$blob='VARBINARY(MAX)';
break;
default:
$blob='BLOB';
break;
}
$db->createCommand()->createTable($tableName,array(
'id'=>'CHAR(32) PRIMARY KEY',
'expire'=>'integer',
'data'=>$blob,
));
}
Creates the session DB table.
public boolean destroySession(string $id)
| ||
$id | string | session ID |
{return} | boolean | whether session is destroyed successfully |
public function destroySession($id)
{
$this->getDbConnection()->createCommand()
->delete($this->sessionTableName,'id=:id',array(':id'=>$id));
return true;
}
Session destroy handler. Do not call this method directly.
public boolean gcSession(integer $maxLifetime)
| ||
$maxLifetime | integer | the number of seconds after which data will be seen as 'garbage' and cleaned up. |
{return} | boolean | whether session is GCed successfully |
public function gcSession($maxLifetime)
{
$this->getDbConnection()->createCommand()
->delete($this->sessionTableName,'expire<:expire',array(':expire'=>time()));
return true;
}
Session GC (garbage collection) handler. Do not call this method directly.
protected CDbConnection getDbConnection()
| ||
{return} | CDbConnection | the DB connection instance |
protected function getDbConnection()
{
if($this->_db!==null)
return $this->_db;
elseif(($id=$this->connectionID)!==null)
{
if(($this->_db=Yii::app()->getComponent($id)) instanceof CDbConnection)
return $this->_db;
else
throw new CException(Yii::t('yii','CDbHttpSession.connectionID "{id}" is invalid. Please make sure it refers to the ID of a CDbConnection application component.',
array('{id}'=>$id)));
}
else
{
$dbFile=Yii::app()->getRuntimePath().DIRECTORY_SEPARATOR.'session-'.Yii::getVersion().'.db';
return $this->_db=new CDbConnection('sqlite:'.$dbFile);
}
}
public boolean getUseCustomStorage()
| ||
{return} | boolean | whether to use custom storage. |
public function getUseCustomStorage()
{
return true;
}
Returns a value indicating whether to use custom session storage. This method overrides the parent implementation and always returns true.
public boolean openSession(string $savePath, string $sessionName)
| ||
$savePath | string | session save path |
$sessionName | string | session name |
{return} | boolean | whether session is opened successfully |
public function openSession($savePath,$sessionName)
{
if($this->autoCreateSessionTable)
{
$db=$this->getDbConnection();
$db->setActive(true);
try
{
$db->createCommand()->delete($this->sessionTableName,'expire<:expire',array(':expire'=>time()));
}
catch(Exception $e)
{
$this->createSessionTable($db,$this->sessionTableName);
}
}
return true;
}
Session open handler. Do not call this method directly.
public string readSession(string $id)
| ||
$id | string | session ID |
{return} | string | the session data |
public function readSession($id)
{
$db=$this->getDbConnection();
if($db->getDriverName()=='sqlsrv' || $db->getDriverName()=='mssql' || $db->getDriverName()=='dblib')
$select='CONVERT(VARCHAR(MAX), data)';
else
$select='data';
$data=$db->createCommand()
->select($select)
->from($this->sessionTableName)
->where('expire>:expire AND id=:id',array(':expire'=>time(),':id'=>$id))
->queryScalar();
return ($data===null || $data===false)?'':$data;
}
Session read handler. Do not call this method directly.
public void regenerateID(boolean $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();
$db=$this->getDbConnection();
$row=$db->createCommand()
->select()
->from($this->sessionTableName)
->where('id=:id',array(':id'=>$oldID))
->queryRow();
if($row!==false)
{
if($deleteOldSession)
$db->createCommand()->update($this->sessionTableName,array(
'id'=>$newID
),'id=:oldID',array(':oldID'=>$oldID));
else
{
$row['id']=$newID;
$db->createCommand()->insert($this->sessionTableName, $row);
}
}
else
{
// shouldn't reach here normally
$db->createCommand()->insert($this->sessionTableName, array(
'id'=>$newID,
'expire'=>time()+$this->getTimeout(),
'data'=>'',
));
}
}
Updates the current session id with a newly generated one. Please refer to https://php.net/session_regenerate_id for more details.
public boolean writeSession(string $id, string $data)
| ||
$id | string | session ID |
$data | string | session data |
{return} | boolean | whether session write is successful |
public function writeSession($id,$data)
{
// exception must be caught in session write handler
// https://us.php.net/manual/en/function.session-set-save-handler.php
try
{
$expire=time()+$this->getTimeout();
$db=$this->getDbConnection();
if($db->getDriverName()=='pgsql')
$data=new CDbExpression($db->quoteValueWithType($data, PDO::PARAM_LOB)."::bytea");
if($db->getDriverName()=='sqlsrv' || $db->getDriverName()=='mssql' || $db->getDriverName()=='dblib')
$data=new CDbExpression('CONVERT(VARBINARY(MAX), '.$db->quoteValue($data).')');
if($db->createCommand()->select('id')->from($this->sessionTableName)->where('id=:id',array(':id'=>$id))->queryScalar()===false)
$db->createCommand()->insert($this->sessionTableName,array(
'id'=>$id,
'data'=>$data,
'expire'=>$expire,
));
else
$db->createCommand()->update($this->sessionTableName,array(
'data'=>$data,
'expire'=>$expire
),'id=:id',array(':id'=>$id));
}
catch(Exception $e)
{
if(YII_DEBUG)
echo $e->getMessage();
// it is too late to log an error message here
return false;
}
return true;
}
Session write handler. Do not call this method directly.
Database performance
Remember that the use of the Yii DB sessions can slow down your application if you don't have autoCreateSessionTable = false on your production server.
It make DELETE from session's table every time session initialize. By default, session's table not indexed;
More at Yii framework forum
autoStart
for god's sake, do not enable session.auto_start = 1 directly in your php.ini or your data column will be always NULL and sessions file will be stored in session_save_path()
Signup or Login in order to comment.