olivierg olivierg - 1 month ago 4
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
    $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.

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!

Answer

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.