检查会话是否设置,如果没有,创建一个? [英] Check if session is set or not, and if not create one?
问题描述
我想检查当前是否设置了会话,如果是,则在不创建会话的情况下允许页面正常运行(什么都不做).
I want to check if a session is currently set, and if so do allow the page to run as normal (do nothing) if not create a session.
我查看了另一个 SO 问题,其中发布了以下代码:
I had a look at another SO question, in which the following code was posted:
if ( empty( $_SESSION['login'] )) { } else { }
最简单的方法是为每个会话设置类似 $_SESSION['a']
的东西,然后运行 if(empty($_SESSION['a']))
检查会话是否存在?
Would the easiest way to do this be to set something like $_SESSION['a']
for each session, and then run if(empty($_SESSION['a']))
to check if a session exists?
再说一次,你能不能在不调用 session_start() 的情况下使用会话变量,从而使它过时(我昨天试过这个,虽然作为回声,而不是检查变量是否在没有执行的情况下执行的 if 语句?意识到需要调用 session_start() 才能回显变量).
Then again, can you use a session variable without invoking session_start() in the first place, thus making it obsolete (I tried this yesterday, as an echo though, not an if statement to check that a variable was carrying through without realizing that session_start() needed to be invoked before I could echo the variable).
可能有一种常用的简单方法,我就是找不到.
There's probably an easy way that's oft used, I just can't seem to find it.
任何帮助将不胜感激!
推荐答案
session_id()
返回标识当前会话的字符串.如果会话尚未初始化,它将返回一个空字符串.
session_id()
returns the string identifying the current session. If a session hasn't been initialized, it will return an empty string.
if(session_id())
{
// session has been started
}
else
{
// session has NOT been started
session_start();
}
这篇关于检查会话是否设置,如果没有,创建一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!