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条)

报告相同问题?

悬赏问题

  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义