如何判断会话是否处于活动状态? [英] How to tell if a session is active?
问题描述
根据请求,您可以通过几种不同的方式来判断会话是否已开始,例如:
Per request, there are a few different ways that you can tell whether or not a session has been started, such as:
$isSessionActive = (session_id() != "");
或者:
$isSessionActive = defined('SID');
但是,如果您启动会话然后将其关闭,它们都将失败; session_id()
将返回上一个会话的ID,而SID
将被定义.同样,如果您已经有一个活动会话,则此时调用session_start()
将生成一个E_NOTICE
.是否有一种明智的方法来检查会话当前是否处于活动状态,而不必求助于输出缓冲,关闭运算符(@session_start()
)或其他类似hacky的东西?
However, these both fail if you start a session, then close it; session_id()
will return the prior session's ID, while SID
will be defined. Likewise, calling session_start()
at this point will generate an E_NOTICE
if you already have a session active. Is there a sane way to check if a session is currently active, without having to resort to output buffering, the shut-up operator (@session_start()
), or something else equally as hacky?
我写了一个补丁,试图使此功能包含在PHP中: http://bugs.php.net/bug.php?id=52982
I wrote a patch to try to get this functionality included in PHP: http://bugs.php.net/bug.php?id=52982
编辑8/29/2011:向PHP 5.4添加了新功能来解决此问题:通过新功能session_status公开会话状态"
EDIT 8/29/2011: New function added to PHP 5.4 to fix this: "Expose session status via new function, session_status"
// as of 8/29/2011
$isSessionActive = (session_status() == PHP_SESSION_ACTIVE);
编辑12/5/11: session_status()在PHP手册上.
EDIT 12/5/11: session_status() on the PHP manual.
推荐答案
查看对原始问题的修改;基本上,PHP 5.4和更高版本现在具有一个名为 session_status()
的函数来解决此问题!
See edits to the original question; basically, PHP 5.4 and above now has a function called session_status()
to solve this problem!
通过新功能session_status公开会话状态"(SVN修订版315745 )
如果您需要PHP 5.4之前的版本中的此功能,请参见 hakre的答案.
If you need this functionality in a pre-PHP 5.4 version, see hakre's answer.
这篇关于如何判断会话是否处于活动状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!