PHP多个OR,如果条件 [英] PHP multiple OR in if condition

查看:195
本文介绍了PHP多个OR,如果条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检入PHP代码,以确定我的用户是否具有执行某项操作所需的权限,但是我的条件无法正常工作。我可能误会了AND / OR。

I'm trying to check in my PHP code if my user has the necessary rights to perform an action but my conditions wont work. I'm probably misunderstanding the AND/OR. May I require your help please.

实际上,我有:

if ( !in_array('ADMIN',$_SESSION['roles']) || !in_array('MANAGEMENT',$_SESSION['roles']) || $requester != $_SESSION['tnumber'] ) {
                            echo "you are not allowed to XXXX !";
                    } else {
      // allowed
}

I'我用OR(||)设置了这3个条件,但是失败了。

I've put these 3 conditions with ORs (||) but it's failing.

我想说的是:


  1. 如果用户没有'ADMIN'或'MANAGEMENT'权限( $ SESSION ['roles'] 数组中的值)

  2. 或者如果用户不是请求者( $ requester 应该与 $ _ SESSION [' tnumber']

  1. If the user doesn't have 'ADMIN' or 'MANAGEMENT' rights (value in the $SESSION['roles'] array)
  2. Or if the user is not the requester ($requester should be the same as $_SESSION['tnumber']

然后他应该有一条消息,说他不允许。

Then he should have a message saying that he's not allowed.

否则(如果他拥有ADMIN权限或MANAGEMENT权限,或者他是请求者),则它应该起作用。

Otherwise (if he's got ADMIN rights, or MANAGEMENT rights, or he is the requester), then it should work.

我可以更改条件来满足此请求吗?

How can I change my condition to fulfill this request ?

谢谢,
致谢!

Thanks, Regards!

推荐答案

if(p || q || r)这样的条件下,整个 if 语句的评估结果为 true true 。如果您没有管理角色,则!in_array('MANAGEMENT',$ _ SESSION ['roles'])将为 true ,因此访问将被拒绝。

In a condition like if (p || q || r), the whole if statement evaluates to true if at least one of the three conditions is true. If you don't have MANAGEMENT role, then !in_array('MANAGEMENT',$_SESSION['roles']) will be true, hence access will be denied.

我建议您反转 if 语句,以便如果为true,则授予访问权限,否则为否认。因此:

I would recommend you to invert the if statement, so that if true, the access is granted, otherwise it's denied. So:

if (in_array('ADMIN', $_SESSION['roles']) || in_array('MANAGEMENT', $_SESSION['roles']) || $requester == $_SESSION['tnumber'] ) {
    // allowed
} else {
    // denied
}

如果将大条件提取到单独的函数中,这也将有助于代码的可读性。

It will also help the readability of your code if you extract the big condition to a separate function.

这篇关于PHP多个OR,如果条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆