如何检查PHP会话是否为空?

2022-08-30 10:50:07

这是不好的做法吗?

if ($_SESSION['something'] == '')
{
    echo 'the session is empty';
}

有没有办法检查它是否为空或未设置?我实际上是这样做的:

if (($_SESSION['something'] == '') || (!isset($_SESSION['something'])) {
    echo 'the session is either empty or doesn\'t exist';
}

只是检查是否存在,而不检查数组中是否存在值!isset$_SESSION['']


答案 1

我会使用 issetempty

session_start();
if(isset($_SESSION['blah']) && !empty($_SESSION['blah'])) {
   echo 'Set and not empty, and no undefined index error!';
}

array_key_exists是用于检查密钥的一个很好的替代方法:isset

session_start();
if(array_key_exists('blah',$_SESSION) && !empty($_SESSION['blah'])) {
    echo 'Set and not empty, and no undefined index error!';
}

请确保在读取或写入会话数组之前进行调用。session_start


答案 2

在访问您不确定其存在的变量之前,请使用 或 (特别是对于数组键)。因此,在第二个示例中更改顺序:issetemptyarray_key_exists

if (!isset($_SESSION['something']) || $_SESSION['something'] == '')

推荐