0 follower

CDbHttpSession

Package system.web
Inheritance class CDbHttpSession » CHttpSession » CApplicationComponent » CComponent
Implements Countable, ArrayAccess, Traversable, IteratorAggregate, IApplicationComponent
Since 1.0
Version $Id$
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.

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.

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 the number of session variables CHttpSession
gCProbability integer the probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance. CHttpSession
isInitialized boolean whether this application component has been initialized (i.e., init() is invoked. 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 '/tmp'. 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
gcSession() Session GC (garbage collection) handler. CDbHttpSession
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 session variables 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 whether this application component has been initialized (i.e., init() is invoked.) 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 '/tmp'. 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
remove() Removes a session variable. 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
getDbConnection() Returns the DB connection instance CDbHttpSession

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 TEXT)

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#72 (show)
protected function createSessionTable($db,$tableName)
{
    
$sql="
CREATE TABLE 
$tableName
(
id CHAR(32) PRIMARY KEY,
expire INTEGER,
data TEXT
)"
;
    
$db->createCommand($sql)->execute();
}

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#181 (show)
public function destroySession($id)
{
    
$id=md5($id);
    
$sql="DELETE FROM {$this->sessionTableName} WHERE id='$id'";
    
$this->getDbConnection()->createCommand($sql)->execute();
    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#195 (show)
public function gcSession($maxLifetime)
{
    
$db=$this->getDbConnection();
    
$db->setActive(true);
    
$sql="DELETE FROM {$this->sessionTableName} WHERE expire<".time();
    
$db->createCommand($sql)->execute();
    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#88 (show)
protected function getDbConnection()
{
    if(
$this->_db!==null)
        return 
$this->_db;
    else if((
$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#62 (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#114 (show)
public function openSession($savePath,$sessionName)
{
    
$db=$this->getDbConnection();
    
$db->setActive(true);

    if(
$this->autoCreateSessionTable)
    {
        
$sql="DELETE FROM {$this->sessionTableName} WHERE expire<".time();
        try
        {
            
$db->createCommand($sql)->execute();
        }
        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#140 (show)
public function readSession($id)
{
    
$now=time();
    
$id=md5($id);
    
$sql="
SELECT data FROM 
{$this->sessionTableName}
WHERE expire>
$now AND id='$id'
"
;
    
$data=$this->getDbConnection()->createCommand($sql)->queryScalar();
    return 
$data===false?'':$data;
}

Session read handler. Do not call this method directly.

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#159 (show)
public function writeSession($id,$data)
{
    
$expire=time()+$this->getTimeout();
    
$id=md5($id);
    
$db=$this->getDbConnection();
    
$sql="SELECT id FROM {$this->sessionTableName} WHERE id='$id'";
    if(
$db->createCommand($sql)->queryScalar()===false)
        
$sql="INSERT INTO {$this->sessionTableName} (id, data, expire) VALUES ('$id', :data, $expire)";
    else
        
$sql="UPDATE {$this->sessionTableName} SET expire=$expire, data=:data WHERE id='$id'";
    
$command=$db->createCommand($sql);
    
$command->bindParam(':data',$data);
    
$command->execute();
    return 
true;
}

Session write handler. Do not call this method directly.