0 follower

CDbHttpSession

Package system.web
Inheritance class CDbHttpSession » CHttpSession » CApplicationComponent » CComponent
Implements Countable, ArrayAccess, Traversable, IteratorAggregate, IApplicationComponent
Since 1.0
Source Code framework/web/CDbHttpSession.php
CDbHttpSession extends CHttpSession by using database as session data storage.

CDbHttpSession stores session data in a DB table named 'YiiSession'. The table name can be changed by setting sessionTableName. If the table does not exist, it will be automatically created if autoCreateSessionTable is set true.

The following is the table structure:

CREATE TABLE YiiSession
(
    id CHAR(32) PRIMARY KEY,
    expire INTEGER,
    data BLOB
)
Where 'BLOB' refers to the BLOB-type of your preffered database.

Note that if your session IDs are more than 32 characters (can be changed via session.hash_bits_per_character or session.hash_function) you should modify SQL schema accordingly.

CDbHttpSession relies on PDO to access database.

By default, it will use an SQLite3 database named 'session-YiiVersion.db' under the application runtime directory. You can also specify connectionID so that it makes use of a DB application component to access database.

When using CDbHttpSession in a production server, we recommend you pre-create the session DB table and set autoCreateSessionTable to be false. This will greatly improve the performance. You may also create a DB index for the 'expire' column in the session table to further improve the performance.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined 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 http://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

Protected Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
dbConnection CDbConnection the DB connection instance CDbHttpSession

Public Methods

Hide inherited methods

MethodDescriptionDefined 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 http://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

Protected Methods

Hide inherited methods

MethodDescriptionDefined 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

Property Details

autoCreateSessionTable property
public boolean $autoCreateSessionTable;

whether the session DB table should be automatically created if not exists. Defaults to true.

See Also

connectionID property
public string $connectionID;

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.

dbConnection property read-only

the DB connection instance

sessionTableName property
public string $sessionTableName;

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)
useCustomStorage property read-only
public boolean getUseCustomStorage()

Returns a value indicating whether to use custom session storage. This method overrides the parent implementation and always returns true.

Method Details

createSessionTable() method
protected void createSessionTable(CDbConnection $db, string $tableName)
$db CDbConnection the database connection
$tableName string the name of the table to be created
Source Code: framework/web/CDbHttpSession.php#139 (show)
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.

destroySession() method
public boolean destroySession(string $id)
$id string session ID
{return} boolean whether session is destroyed successfully
Source Code: framework/web/CDbHttpSession.php#281 (show)
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.

gcSession() method
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
Source Code: framework/web/CDbHttpSession.php#294 (show)
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.

getDbConnection() method
protected CDbConnection getDbConnection()
{return} CDbConnection the DB connection instance
Source Code: framework/web/CDbHttpSession.php#169 (show)
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);
    }
}

getUseCustomStorage() method
public boolean getUseCustomStorage()
{return} boolean whether to use custom storage.
Source Code: framework/web/CDbHttpSession.php#83 (show)
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.

openSession() method
public boolean openSession(string $savePath, string $sessionName)
$savePath string session save path
$sessionName string session name
{return} boolean whether session is opened successfully
Source Code: framework/web/CDbHttpSession.php#195 (show)
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.

readSession() method
public string readSession(string $id)
$id string session ID
{return} string the session data
Source Code: framework/web/CDbHttpSession.php#219 (show)
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.

regenerateID() method (available since v1.1.8)
public void regenerateID(boolean $deleteOldSession=false)
$deleteOldSession boolean Whether to delete the old associated session file or not.
Source Code: framework/web/CDbHttpSession.php#94 (show)
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 http://php.net/session_regenerate_id for more details.

writeSession() method
public boolean writeSession(string $id, string $data)
$id string session ID
$data string session data
{return} boolean whether session write is successful
Source Code: framework/web/CDbHttpSession.php#241 (show)
public function writeSession($id,$data)
{
    
// exception must be caught in session write handler
    // http://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($dataPDO::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.