确定 $_SESSION 超全局变量是否存在于 PHP 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10855972/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:13:47  来源:igfitidea点击:

Determine if $_SESSION superglobal exists in PHP

phpsession

提问by Anas

I want to do something like this:

我想做这样的事情:

if ($_SESSION['errors'] exists)
{
    //Do stuff
}

I want to create a session on page1 and then go to page2 where it will check for errors, if there are errors it returns to page1 with the errors.

我想在第 1 页上创建一个会话,然后转到第 2 页,它将检查错误,如果有错误,则返回第 1 页并显示错误。

But page1 will give errors if the variable hasn't been created yet on page 2.

但是如果变量尚未在第 2 页上创建,则第 1 页会出错。

If I do $_SESSION['errors'] == ""on page1 it will reset the variable so that's no good.

如果我$_SESSION['errors'] == ""在 page1 上这样做,它会重置变量,这样就不好了。

回答by Anas

if (isset($_SESSION['errors']))
{
    //Do stuff
}

回答by Pier-Alexandre Bouchard

use isset()and empty()php function.

使用isset()empty()php函数。

if (isset($_SESSION['errors']) && !empty($_SESSION['errors'])) {
    // ...
} 

回答by Ashish Bafna

if (!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) {
     // do stuff
}