dream5694 2011-10-05 01:45
浏览 21
已采纳

什么是最好的? 许多小会话值或一个大的值? PHP

I have about 15-20 permission settings that are loaded when a user logs in. These are each stored as a session with a value of 1 or 0.

I'm wondering, would it be better to have one session like $_SESSION['permissions'] with a value of: dothis:0,dothat:1,doanother:1, etc. (one large string) which I can explode and seperate later on with PHP, or would it be best to have all these as separate sessions with just a value of 1 or 0?

  • 写回答

2条回答 默认 最新

  • duandaiqin6080 2011-10-05 01:49
    关注

    Rather than a string to parse, store them as an array in $_SESSION. This makes it much easier to modify individual permissions without having to do piles of string operations.

    session_start();
    $_SESSION['permissions'] = array();
    $_SESSION['permissions']['dothis'] = TRUE;
    $_SESSION['permissions']['dothat'] = FALSE;
    $_SESSION['permissions']['doanother'] = TRUE;
    

    Addendum

    You might have figured this out already, but I thought I would add that it is easiest to interact with these via a few tiny functions. These will save a lot of typing (and typing errors), and make sure the values all end up as booleans.

    function grant($permission) {
      $_SESSION['permissions'][$permission] = TRUE;
    }
    function revoke($permission) {
      $_SESSION['permissions'][$permission] = FALSE;
    }
    // Test if the user is allowed to do $permission
    // FALSE if the permission isn't set
    function user_can($permission) {
      return isset($_SESSION['permissions'][$permission]) ? $_SESSION['permissions'][$permission] : FALSE;
    }
    

    The you can just call them as:

    grant('dothis');
    revoke('dothat');
    if (user_can('doanother')) {
       // congratulations you're allowed
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来