CHttpSession

优质
小牛编辑
129浏览
2023-12-01
所有包 | 属性 | 方法
system.web
继承class CHttpSession » CApplicationComponent » CComponent
实现IApplicationComponent, IteratorAggregate, Traversable, ArrayAccess, Countable
子类CCacheHttpSession, CDbHttpSession
源自1.0
版本$Id: CHttpSession.php 3511 2011-12-27 00:02:53Z alexander.makarow $
源码framework/web/CHttpSession.php
CHttpSession provides session-level data management and the related configurations.

To start the session, call open(); To complete and send out session data, call close(); To destroy the session, call destroy().

If autoStart is set true, the session will be started automatically when the application component is initialized by the application.

CHttpSession can be used like an array to set and get session data. For example,
$session=new CHttpSession;$session->open();$value1=$session['name1'];  // get session variable 'name1'$value2=$session['name2'];  // get session variable 'name2'foreach($session as $name=>$value) // traverse all session variables$session['name3']=$value3;  // set session variable 'name3'


The following configurations are available for session:
  • sessionID;
  • sessionName;
  • autoStart;
  • savePath;
  • cookieParams;
  • gcProbability;
  • cookieMode;
  • useTransparentSessionID;
  • timeout.
See the corresponding setter and getter documentation for more information. Note, these properties must be set before the session is started.

CHttpSession can be extended to support customized session storage. Override openSession, closeSession, readSession, writeSession, destroySession and gcSession and set useCustomStorage to true. Then, the session data will be stored and retrieved using the above methods.

CHttpSession is a Web application component that can be accessed via CWebApplication::getSession().

公共属性

隐藏继承属性

属性类型描述定义在
autoStartbooleanwhether the session should be automatically started when the session application component is initialized, defaults to true.CHttpSession
behaviorsarray这个应用组件附加的行为。 这此行为将在应用组件调用init时附加在应用组件上。 请参照CModel::behaviors如何指定此属性值。CApplicationComponent
cookieModestringhow to use cookie to store session ID.CHttpSession
cookieParamsarraythe session cookie parameters.CHttpSession
countintegerReturns the number of items in the session.CHttpSession
gCProbabilityintegerthe probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.CHttpSession
isInitializedboolean检查应用组件是否已经初始化。CApplicationComponent
isStartedbooleanwhether the session has startedCHttpSession
iteratorCHttpSessionIteratorReturns an iterator for traversing the session variables.CHttpSession
keysarraythe list of session variable namesCHttpSession
savePathstringthe current session save path, defaults to '/tmp'.CHttpSession
sessionIDstringthe current session IDCHttpSession
sessionNamestringthe current session nameCHttpSession
timeoutintegerthe number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds.CHttpSession
useCustomStoragebooleanReturns a value indicating whether to use custom session storage.CHttpSession
useTransparentSessionIDbooleanwhether transparent sid support is enabled or not, defaults to false.CHttpSession

公共方法

隐藏继承方法

方法描述定义在
__call()如果类中没有调的方法名,则调用这个方法。CComponent
__get()返回一个属性值、一个事件处理程序列表或一个行为名称。CComponent
__isset()检查一个属性是否为null。CComponent
__set()设置一个组件的属性值。CComponent
__unset()设置一个组件的属性为null。CComponent
add()Adds a session variable.CHttpSession
asa()返回这个名字的行为对象。CComponent
attachBehavior()附加一个行为到组件。CComponent
attachBehaviors()附加一个行为列表到组件。CComponent
attachEventHandler()为事件附加一个事件处理程序。CComponent
canGetProperty()确定属性是否可读。CComponent
canSetProperty()确定属性是否可写。CComponent
clear()Removes all session variablesCHttpSession
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.CHttpSession
detachBehavior()从组件中分离一个行为。CComponent
detachBehaviors()从组件中分离所有行为。CComponent
detachEventHandler()分离一个存在的事件处理程序。CComponent
disableBehavior()禁用一个附加行为。CComponent
disableBehaviors()禁用组件附加的所有行为。CComponent
enableBehavior()启用一个附加行为。CComponent
enableBehaviors()启用组件附加的所有行为。CComponent
evaluateExpression()计算一个PHP表达式,或根据组件上下文执行回调。CComponent
gcSession()Session GC (garbage collection) handler.CHttpSession
get()Returns the session variable value with the session variable name.CHttpSession
getCookieMode()返回how to use cookie to store session ID. Defaults to 'Allow'.CHttpSession
getCookieParams()返回the session cookie parameters.CHttpSession
getCount()Returns the number of items in the session.CHttpSession
getEventHandlers()返回一个事件的附加处理程序列表。CComponent
getGCProbability()返回the probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.CHttpSession
getIsInitialized()检查应用组件是否已经初始化。CApplicationComponent
getIsStarted()检查whether the session has startedCHttpSession
getIterator()Returns an iterator for traversing the session variables.CHttpSession
getKeys()返回the list of session variable namesCHttpSession
getSavePath()返回the current session save path, defaults to '/tmp'.CHttpSession
getSessionID()返回the current session IDCHttpSession
getSessionName()返回the current session nameCHttpSession
getTimeout()返回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.CHttpSession
getUseTransparentSessionID()返回whether transparent sid support is enabled or not, defaults to false.CHttpSession
hasEvent()确定一个事件是否定义。CComponent
hasEventHandler()检查事件是否有附加的处理程序。CComponent
hasProperty()确定属性是否被定义。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.CHttpSession
raiseEvent()发起一个事件。CComponent
readSession()Session read handler.CHttpSession
regenerateID()Updates the current session id with a newly generated one .CHttpSession
remove()Removes a session variable.CHttpSession
setCookieMode()设置how to use cookie to store session ID. Valid values include 'none', 'allow' and 'only'.CHttpSession
setCookieParams()Sets the session cookie parameters.CHttpSession
setGCProbability()设置the probability (percentage) that the gc (garbage collection) process is started on every session initialization.CHttpSession
setSavePath()设置the current session save pathCHttpSession
setSessionID()设置the session ID for the current sessionCHttpSession
setSessionName()设置the session name for the current session, must be an alphanumeric string, defaults to PHPSESSIDCHttpSession
setTimeout()设置the number of seconds after which data will be seen as 'garbage' and cleaned upCHttpSession
setUseTransparentSessionID()设置whether transparent sid support is enabled or not.CHttpSession
toArray()CHttpSession
writeSession()Session write handler.CHttpSession

属性详细

autoStart 属性 public boolean $autoStart;

whether the session should be automatically started when the session application component is initialized, defaults to true.

cookieMode 属性 public string getCookieMode()
public void setCookieMode(string $value)

how to use cookie to store session ID. Defaults to 'Allow'.

cookieParams 属性 public array getCookieParams()
public void setCookieParams(array $value)

the session cookie parameters.

参见

  • http://us2.php.net/manual/en/function.session-get-cookie-params.php
count 属性 只读 public integer getCount()

Returns the number of items in the session.

gCProbability 属性 public integer getGCProbability()
public void setGCProbability(integer $value)

the probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.

isStarted 属性 只读 public boolean getIsStarted()

whether the session has started

iterator 属性 只读 public CHttpSessionIterator getIterator()

Returns an iterator for traversing the session variables. This method is required by the interface IteratorAggregate.

keys 属性 只读 public array getKeys()

the list of session variable names

savePath 属性 public string getSavePath()
public void setSavePath(string $value)

the current session save path, defaults to '/tmp'.

sessionID 属性 public string getSessionID()
public void setSessionID(string $value)

the current session ID

sessionName 属性 public string getSessionName()
public void setSessionName(string $value)

the current session name

timeout 属性 public integer getTimeout()
public void setTimeout(integer $value)

the number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds.

useCustomStorage 属性 只读 public boolean getUseCustomStorage()

Returns a value indicating whether to use custom session storage. This method should be overriden to return true if custom session storage handler should be used. If returning true, make sure the methods openSession, closeSession, readSession, writeSession, destroySession, and gcSession are overridden in child class, because they will be used as the callback handlers. The default implementation always return false.

useTransparentSessionID 属性 public boolean getUseTransparentSessionID()
public void setUseTransparentSessionID(boolean $value)

whether transparent sid support is enabled or not, defaults to false.

方法详细

add() 方法
public void add(mixed $key, mixed $value)
$keymixedsession variable name
$valuemixedsession variable value
源码: framework/web/CHttpSession.php#486 (显示) publicfunctionadd($key,$value)
{
$_SESSION[$key]=$value;
}

Adds a session variable. Note, if the specified name already exists, the old value will be removed first.

clear() 方法
public void clear()
源码: framework/web/CHttpSession.php#511 (显示) publicfunctionclear()
{
foreach(array_keys($_SESSION)as$key)
unset($_SESSION[$key]);
}

Removes all session variables

close() 方法
public void close()
源码: framework/web/CHttpSession.php#132 (显示) publicfunctionclose()
{
if(session_id()!=='')
@session_write_close();
}

Ends the current session and store session data.

closeSession() 方法
public boolean closeSession()
{return}booleanwhether session is closed successfully
源码: framework/web/CHttpSession.php#362 (显示) publicfunctioncloseSession()
{
returntrue;
}

Session close handler. This method should be overridden if useCustomStorage is set true. Do not call this method directly.

contains() 方法
public boolean contains(mixed $key)
$keymixedsession variable name
{return}booleanwhether there is the named session variable
源码: framework/web/CHttpSession.php#521 (显示) publicfunctioncontains($key)
{
returnisset($_SESSION[$key]);
}
count() 方法
public integer count()
{return}integernumber of items in the session.
源码: framework/web/CHttpSession.php#442 (显示) publicfunctioncount()
{
return$this->getCount();
}

Returns the number of items in the session. This method is required by Countable interface.

destroy() 方法
public void destroy()
源码: framework/web/CHttpSession.php#141 (显示) publicfunctiondestroy()
{
if(session_id()!=='')
{
@session_unset();
@session_destroy();
}
}

Frees all session variables and destroys all data registered to a session.

destroySession() 方法
public boolean destroySession(string $id)
$idstringsession ID
{return}booleanwhether session is destroyed successfully
源码: framework/web/CHttpSession.php#399 (显示) publicfunctiondestroySession($id)
{
returntrue;
}

Session destroy handler. This method should be overridden if useCustomStorage is set true. Do not call this method directly.

gcSession() 方法
public boolean gcSession(integer $maxLifetime)
$maxLifetimeintegerthe number of seconds after which data will be seen as 'garbage' and cleaned up.
{return}booleanwhether session is GCed successfully
源码: framework/web/CHttpSession.php#411 (显示) publicfunctiongcSession($maxLifetime)
{
returntrue;
}

Session GC (garbage collection) handler. This method should be overridden if useCustomStorage is set true. Do not call this method directly.

get() 方法 (可用自 v1.1.2)
public mixed get(mixed $key, mixed $defaultValue=NULL)
$keymixedthe session variable name
$defaultValuemixedthe default value to be returned when the session variable does not exist.
{return}mixedthe session variable value, or $defaultValue if the session variable does not exist.
源码: framework/web/CHttpSession.php#464 (显示) publicfunctionget($key,$defaultValue=null)
{
returnisset($_SESSION[$key])?$_SESSION[$key]:$defaultValue;
}

Returns the session variable value with the session variable name. This method is very similar to itemAt and offsetGet, except that it will return $defaultValue if the session variable does not exist.

getCookieMode() 方法
public string getCookieMode()
{return}stringhow to use cookie to store session ID. Defaults to 'Allow'.
源码: framework/web/CHttpSession.php#252 (显示) publicfunctiongetCookieMode()
{
if(ini_get('session.use_cookies')==='0')
return'none';
elseif(ini_get('session.use_only_cookies')==='0')
return'allow';
else
return'only';
}
getCookieParams() 方法
public array getCookieParams()
{return}arraythe session cookie parameters.
源码: framework/web/CHttpSession.php#226 (显示) publicfunctiongetCookieParams()
{
returnsession_get_cookie_params();
}

参见

  • http://us2.php.net/manual/en/function.session-get-cookie-params.php
getCount() 方法
public integer getCount()
{return}integerthe number of session variables
源码: framework/web/CHttpSession.php#432 (显示) publicfunctiongetCount()
{
returncount($_SESSION);
}

Returns the number of items in the session.

getGCProbability() 方法
public integer getGCProbability()
{return}integerthe probability (percentage) that the gc (garbage collection) process is started on every session initialization, defaults to 1 meaning 1% chance.
源码: framework/web/CHttpSession.php#289 (显示) publicfunctiongetGCProbability()
{
return(int)ini_get('session.gc_probability');
}
getIsStarted() 方法
public boolean getIsStarted()
{return}booleanwhether the session has started
源码: framework/web/CHttpSession.php#153 (显示) publicfunctiongetIsStarted()
{
returnsession_id()!=='';
}
getIterator() 方法
public CHttpSessionIterator getIterator()
{return}CHttpSessionIteratoran iterator for traversing the session variables.
源码: framework/web/CHttpSession.php#423 (显示) publicfunctiongetIterator()
{
returnnewCHttpSessionIterator;
}

Returns an iterator for traversing the session variables. This method is required by the interface IteratorAggregate.

getKeys() 方法
public array getKeys()
{return}arraythe list of session variable names
源码: framework/web/CHttpSession.php#450 (显示) publicfunctiongetKeys()
{
returnarray_keys($_SESSION);
}
getSavePath() 方法
public string getSavePath()
{return}stringthe current session save path, defaults to '/tmp'.
源码: framework/web/CHttpSession.php#204 (显示) publicfunctiongetSavePath()
{
returnsession_save_path();
}
getSessionID() 方法
public string getSessionID()
{return}stringthe current session ID
源码: framework/web/CHttpSession.php#161 (显示) publicfunctiongetSessionID()
{
returnsession_id();
}
getSessionName() 方法
public string getSessionName()
{return}stringthe current session name
源码: framework/web/CHttpSession.php#188 (显示) publicfunctiongetSessionName()
{
returnsession_name();
}
getTimeout() 方法
public integer getTimeout()
{return}integerthe number of seconds after which data will be seen as 'garbage' and cleaned up, defaults to 1440 seconds.
源码: framework/web/CHttpSession.php#330 (显示) publicfunctiongetTimeout()
{
return(int)ini_get('session.gc_maxlifetime');
}
getUseCustomStorage() 方法
public boolean getUseCustomStorage()
{return}booleanwhether to use custom storage.
源码: framework/web/CHttpSession.php#102 (显示) publicfunctiongetUseCustomStorage()
{
returnfalse;
}

Returns a value indicating whether to use custom session storage. This method should be overriden to return true if custom session storage handler should be used. If returning true, make sure the methods openSession, closeSession, readSession, writeSession, destroySession, and gcSession are overridden in child class, because they will be used as the callback handlers. The default implementation always return false.

getUseTransparentSessionID() 方法
public boolean getUseTransparentSessionID()
{return}booleanwhether transparent sid support is enabled or not, defaults to false.
源码: framework/web/CHttpSession.php#314 (显示) publicfunctiongetUseTransparentSessionID()
{
returnini_get('session.use_trans_sid')==1;
}
init() 方法
public void init()
源码: framework/web/CHttpSession.php#85 (显示) publicfunctioninit()
{
parent::init();
if($this->autoStart)
$this->open();
register_shutdown_function(array($this,'close'));
}

Initializes the application component. This method is required by IApplicationComponent and is invoked by application.

itemAt() 方法
public mixed itemAt(mixed $key)
$keymixedthe session variable name
{return}mixedthe session variable value, null if no such variable exists
源码: framework/web/CHttpSession.php#475 (显示) publicfunctionitemAt($key)
{
returnisset($_SESSION[$key])?$_SESSION[$key]:null;
}

Returns the session variable value with the session variable name. This method is exactly the same as offsetGet.

offsetExists() 方法
public boolean offsetExists(mixed $offset)
$offsetmixedthe offset to check on
{return}boolean
源码: framework/web/CHttpSession.php#539 (显示) publicfunctionoffsetExists($offset)
{
returnisset($_SESSION[$offset]);
}

This method is required by the interface ArrayAccess.

offsetGet() 方法
public mixed offsetGet(integer $offset)
$offsetintegerthe offset to retrieve element.
{return}mixedthe element at the offset, null if no element is found at the offset
源码: framework/web/CHttpSession.php#549 (显示) publicfunctionoffsetGet($offset)
{
returnisset($_SESSION[$offset])?$_SESSION[$offset]:null;
}

This method is required by the interface ArrayAccess.

offsetSet() 方法
public void offsetSet(integer $offset, mixed $item)
$offsetintegerthe offset to set element
$itemmixedthe element value
源码: framework/web/CHttpSession.php#559 (显示) publicfunctionoffsetSet($offset,$item)
{
$_SESSION[$offset]=$item;
}

This method is required by the interface ArrayAccess.

offsetUnset() 方法
public void offsetUnset(mixed $offset)
$offsetmixedthe offset to unset element
源码: framework/web/CHttpSession.php#568 (显示) publicfunctionoffsetUnset($offset)
{
unset($_SESSION[$offset]);
}

This method is required by the interface ArrayAccess.

open() 方法
public void open()
源码: framework/web/CHttpSession.php#110 (显示) publicfunctionopen()
{
if($this->getUseCustomStorage())
@session_set_save_handler(array($this,'openSession'),array($this,'closeSession'),array($this,'readSession'),array($this,'writeSession'),array($this,'destroySession'),array($this,'gcSession'));

@session_start();
if(YII_DEBUG&&session_id()=='')
{
$message=Yii::t('yii','Failedtostartsession.');
if(function_exists('error_get_last'))
{
$error=error_get_last();
if(isset($error['message']))
$message=$error['message'];
}
Yii::log($message,CLogger::LEVEL_WARNING,'system.web.CHttpSession');
}
}

Starts the session if it has not started yet.

openSession() 方法
public boolean openSession(string $savePath, string $sessionName)
$savePathstringsession save path
$sessionNamestringsession name
{return}booleanwhether session is opened successfully
源码: framework/web/CHttpSession.php#351 (显示) publicfunctionopenSession($savePath,$sessionName)
{
returntrue;
}

Session open handler. This method should be overridden if useCustomStorage is set true. Do not call this method directly.

readSession() 方法
public string readSession(string $id)
$idstringsession ID
{return}stringthe session data
源码: framework/web/CHttpSession.php#374 (显示) publicfunctionreadSession($id)
{
return'';
}

Session read handler. This method should be overridden if useCustomStorage is set true. Do not call this method directly.

regenerateID() 方法 (可用自 v1.1.8)
public void regenerateID(boolean $deleteOldSession=false)
$deleteOldSessionbooleanWhether to delete the old associated session file or not.
源码: framework/web/CHttpSession.php#180 (显示) publicfunctionregenerateID($deleteOldSession=false)
{
session_regenerate_id($deleteOldSession);
}

Updates the current session id with a newly generated one . Please refer to http://php.net/session_regenerate_id for more details.

remove() 方法
public mixed remove(mixed $key)
$keymixedthe name of the session variable to be removed
{return}mixedthe removed value, null if no such session variable.
源码: framework/web/CHttpSession.php#496 (显示) publicfunctionremove($key)
{
if(isset($_SESSION[$key]))
{
$value=$_SESSION[$key];
unset($_SESSION[$key]);
return$value;
}
else
returnnull;
}

Removes a session variable.

setCookieMode() 方法
public void setCookieMode(string $value)
$valuestringhow to use cookie to store session ID. Valid values include 'none', 'allow' and 'only'.
源码: framework/web/CHttpSession.php#265 (显示) publicfunctionsetCookieMode($value)
{
if($value==='none')
{
ini_set('session.use_cookies','0');
ini_set('session.use_only_cookies','0');
}
elseif($value==='allow')
{
ini_set('session.use_cookies','1');
ini_set('session.use_only_cookies','0');
}
elseif($value==='only')
{
ini_set('session.use_cookies','1');
ini_set('session.use_only_cookies','1');
}
else
thrownewCException(Yii::t('yii','CHttpSession.cookieModecanonlybe"none","allow"or"only".'));
}
setCookieParams() 方法
public void setCookieParams(array $value)
$valuearraycookie parameters, valid keys include: lifetime, path, domain, secure.
源码: framework/web/CHttpSession.php#238 (显示) publicfunctionsetCookieParams($value)
{
$data=session_get_cookie_params();
extract($data);
extract($value);
if(isset($httponly))
session_set_cookie_params($lifetime,$path,$domain,$secure,$httponly);
else
session_set_cookie_params($lifetime,$path,$domain,$secure);
}

Sets the session cookie parameters. The effect of this method only lasts for the duration of the script. Call this method before the session starts.

参见

  • http://us2.php.net/manual/en/function.session-set-cookie-params.php
setGCProbability() 方法
public void setGCProbability(integer $value)
$valueintegerthe probability (percentage) that the gc (garbage collection) process is started on every session initialization.
源码: framework/web/CHttpSession.php#298 (显示) publicfunctionsetGCProbability($value)
{
$value=(int)$value;
if($value>=0&&$value<=100)
{
ini_set('session.gc_probability',$value);
ini_set('session.gc_divisor','100');
}
else
thrownewCException(Yii::t('yii','CHttpSession.gcProbability"{value}"isinvalid.Itmustbeanintegerbetween0and100.',
array('{value}'=>$value)));
}
setSavePath() 方法
public void setSavePath(string $value)
$valuestringthe current session save path
源码: framework/web/CHttpSession.php#213 (显示) publicfunctionsetSavePath($value)
{
if(is_dir($value))
session_save_path($value);
else
thrownewCException(Yii::t('yii','CHttpSession.savePath"{path}"isnotavaliddirectory.',
array('{path}'=>$value)));
}
setSessionID() 方法
public void setSessionID(string $value)
$valuestringthe session ID for the current session
源码: framework/web/CHttpSession.php#169 (显示) publicfunctionsetSessionID($value)
{
session_id($value);
}
setSessionName() 方法
public void setSessionName(string $value)
$valuestringthe session name for the current session, must be an alphanumeric string, defaults to PHPSESSID
源码: framework/web/CHttpSession.php#196 (显示) publicfunctionsetSessionName($value)
{
session_name($value);
}
setTimeout() 方法
public void setTimeout(integer $value)
$valueintegerthe number of seconds after which data will be seen as 'garbage' and cleaned up
源码: framework/web/CHttpSession.php#338 (显示) publicfunctionsetTimeout($value)
{
ini_set('session.gc_maxlifetime',$value);
}
setUseTransparentSessionID() 方法
public void setUseTransparentSessionID(boolean $value)
$valuebooleanwhether transparent sid support is enabled or not.
源码: framework/web/CHttpSession.php#322 (显示) publicfunctionsetUseTransparentSessionID($value)
{
ini_set('session.use_trans_sid',$value?'1':'0');
}
toArray() 方法
public array toArray()
{return}arraythe list of all session variables in array
源码: framework/web/CHttpSession.php#529 (显示) publicfunctiontoArray()
{
return$_SESSION;
}
writeSession() 方法
public boolean writeSession(string $id, string $data)
$idstringsession ID
$datastringsession data
{return}booleanwhether session write is successful
源码: framework/web/CHttpSession.php#387 (显示) publicfunctionwriteSession($id,$data)
{
returntrue;
}

Session write handler. This method should be overridden if useCustomStorage is set true. Do not call this method directly.