php 检查会话是否设置,如果没有,创建一个?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6901547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if session is set or not, and if not create one?
提问by Fireworksable
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.
我想检查当前是否设置了会话,如果是这样,如果不创建会话,则允许页面正常运行(什么都不做)。
I had a look at another SO question, in which the following code was posted:
我查看了另一个 SO 问题,其中发布了以下代码:
if ( empty( $_SESSION['login'] )) { } else { }
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['a']
为每个会话设置类似的东西,然后运行if(empty($_SESSION['a']))
以检查会话是否存在?
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).
再说一次,你能不能在不调用 session_start() 的情况下使用 session 变量,从而使它过时(我昨天试过这个,作为回声,而不是 if 语句来检查变量是否正在执行而没有意识到 session_start () 需要在我可以回显变量之前调用)。
There's probably an easy way that's oft used, I just can't seem to find it.
可能有一种经常使用的简单方法,我似乎找不到它。
Any help would be greatly appreciated!
任何帮助将不胜感激!
回答by Chris Hepner
session_id()
returns the string identifying the current session. If a session hasn't been initialized, it will return an empty string.
session_id()
返回标识当前会话的字符串。如果会话尚未初始化,它将返回一个空字符串。
if(session_id())
{
// session has been started
}
else
{
// session has NOT been started
session_start();
}