Reputation: 351
I'm like to use this IF to redirect user based on permissions. But user is all time redirected to dashboard.
Actually i have set:
$perm_edit = '0';
$user_level = '1';
if ($perm_edit !== 1 || $user_level !== 1) {
header("Location: $url/dash.php?error=1"); exit;
}
|| operator require only one condition to go ahead.
What do I wrong?
Upvotes: 0
Views: 63
Reputation: 13273
It is because you are using the not identical to operator (!==
). It does not do type juggling, which is what you need in this case.
In order to find out if two values, of different types, are equivalent, you must use the not equal to operator (!=
):
if ($perm_edit != 1 || $user_level != 1) {
header("Location: $url/dash.php?error=1");
exit;
}
Another way to write that is:
if ( ! $perm_edit || ! $user_level) {
header("Location: $url/dash.php?error=1");
exit;
}
The reason that works is because PHP juggles the types. In other words, it turns 0
into false
and 1
into true
, and then the !
operator (also called the NOT operator) turns it into the opposite.
You should read up on comparison operators and operators in general.
Upvotes: 1
Reputation: 7930
The triple comparison operators are "strict", meaning they check type as well as value. You are comparing strings to numbers, which means they will always be false. Either turn them both into numbers, or just use double comparisons: $perm_edit != 1
Upvotes: 6