drox90250557 2009-10-05 12:36
浏览 12
已采纳

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

Is this bad practice?

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

Is there a way to check if its empty or it is not set? I'm actualy doing this:

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

Does !isset just checks if a $_SESSION[''] exist and doesn't check if, is there are values in the array or not

  • 写回答

8条回答 默认 最新

  • doujieyu7062 2009-10-05 12:41
    关注

    I would use isset and empty:

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

    array_key_exists is a nice alternative to using isset to check for keys:

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

    Make sure you're calling session_start before reading from or writing to the session array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解
  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题