I am currently writing my own permission class for my forum and i've run into a small problem that I really can understand.
I have the following function:
function editTopic($perm_edit_topic, $id, $user_id, $my_id, $permission){
if($perm_edit_topic == true && $user_id == $my_id OR $permission == 0 XOR $permission == 1){
echo '<a href="/forum/newtopic.php?edit='.$id.'" class="buttonPro" data-toggle="tooltip" data-placement="top" title="Edit"><i class="fa fa-pencil-square-o fa-fw"></i></a>';
}
}
I want the IF statement to do the following:
If $perm_edit_topic
is set to TRUE and the $user_id
(which is the stored user_id
from the topic) is the user id of the viewing user OR the permission id is either 0 or 1 (where 0 is admin and 1 is moderator).
This works okay. Only the owner of the topic and the admin and mods can edit. But if I set the $perm_edit_topic
to FALSE
for the moderator, they can still edit it.
Did I do something wrong in my IF
statement?
Replace your condition with this:
$perm_edit_topic == true
has the exact same meaning as$perm_edit_topic
Wrap all of the other conditions inside of parenthesis to control the short circuiting, it is quite unintuitive how it works with this combination of and'ing, or'ing, and xor'ing. If you are not familiar with short circuiting then try running this example: Does PHP have short-circuit evaluation?
Inside the parenthesis any of the conditions being true is enough for the entire expression to be true. Both
$permission == 0
and$permission == 1
cannot be true, it does not make sense to xor them