php 检测PHP会话是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3538513/
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
Detect if PHP session exists
提问by Pablo
Facebook now offer subscriptions to users so you can get realtime updates on changes. If my app receives an update, I plan to store it in the database. I would also like to detect if their session exists. If it does then I could update the data in there too.
Facebook 现在向用户提供订阅服务,因此您可以获得有关更改的实时更新。如果我的应用收到更新,我计划将其存储在数据库中。我还想检测他们的会话是否存在。如果是这样,那么我也可以更新那里的数据。
My session IDs are MD5(fb_id + secret) so I could easily edit their session. The question is how can I detect if the session exists.
我的会话 ID 是 MD5(fb_id + secret),因此我可以轻松编辑他们的会话。问题是如何检测会话是否存在。
采纳答案by Sebastián Grignoli
According to the PHP.net manual:
根据PHP.net 手册:
If
$_SESSION
(or$HTTP_SESSION_VARS
for PHP 4.0.6 or less) is used, useisset()
to check a variable is registered in$_SESSION
.
如果
$_SESSION
(或$HTTP_SESSION_VARS
对于 PHP 4.0.6 或更低版本)使用,则用于isset()
检查变量是否已注册到$_SESSION
.
回答by Reign.85
I use a combined version:
我使用组合版本:
if(session_id() == '' || !isset($_SESSION)) {
// session isn't started
session_start();
}
回答by Toto
If you are on php 5.4+, it is cleaner to use session_status():
如果您使用的是 php 5.4+,则使用session_status()会更清晰:
if (session_status() == PHP_SESSION_ACTIVE) {
echo 'Session is active';
}
PHP_SESSION_DISABLED
if sessions are disabled.PHP_SESSION_NONE
if sessions are enabled, but none exists.PHP_SESSION_ACTIVE
if sessions are enabled, and one exists.
PHP_SESSION_DISABLED
如果会话被禁用。PHP_SESSION_NONE
如果会话已启用,但不存在。PHP_SESSION_ACTIVE
如果会话已启用,并且存在会话。
回答by Rushabh Koradia
Which method is used to check if SESSION exists or not? Answer: isset($_SESSION['variable_name'])
使用哪种方法检查 SESSION 是否存在?答案:isset($_SESSION['variable_name'])
Example: isset($_SESSION['id'])
示例:isset($_SESSION['id'])
回答by Sabry Suleiman
function is_session_started()
{
if ( php_sapi_name() !== 'cli' ) {
if ( version_compare(phpversion(), '5.4.0', '>=') ) {
return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
} else {
return session_id() === '' ? FALSE : TRUE;
}
}
return FALSE;
}
// Example
if ( is_session_started() === FALSE ) session_start();