olivierg olivierg - 1 year ago 61
PHP Question

PHP multiple OR in if condition

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.

Actually, I have :

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

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

What I want to say is :

  1. If the user doesn't have 'ADMIN' or 'MANAGEMENT' rights (value in the

  2. Or if the user is not the requester (
    should be the same as

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

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 ?


Answer Source

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.

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download