Reputation: 2823
ok, I have set up a basic membership system where I have groups in my db (members, admin and moderator). the groups have 3 fields, id, name and permission. members I have left permission blank, admin has {"admin": 1 "moderator": 1} and moderator has {"moderator": 1}.
I have a simple function in a user.php
file in a folder classes
function
class User {
public function hasPermission($key) {
$group = $this->_db->query("SELECT * FROM groups WHERE id = ?", array($this->data()->group));
if($group->count()) {
$permissions = json_decode($group->first()->permissions, true);
if($permissions[$key] === 1) {
return true;
}
}
return false;
}
}
then in a file admin.php
I have a simple bit of code that should show a echo if the users logged in is admin
ps: I have required the init.php
file that has my classes/User.php
file required so that I do not need to call several files.
code
<?php
}
if($user->hasPermission('admin')) {
echo '<p>You are a admin!</p>';
} else {
echo 'You need to <a href="login.php">log in</a> or <a href="register.php">register</a>!';
}
?>
from this when a admin is logged in a echo should be displayed, unfortunately I am just getting a blank page.
Question
So my question is dose anyone know why this is not working as I have a admin permission set user logged in and am getting nothing on admin.php
?
groups table
users table
Ok so for some reason the You need to log in or register! echo shows it dose not recognise when a admin is logged in.
all im trying to do is allow different groups different page accsess
Upvotes: 0
Views: 229
Reputation: 977
Alright, since my previous answer was deleted.. here's another go.
Your problem is the type-safe comparison you do here:
if($permissions[$key] === true) {
return true;
}
Your array is filled from a json object {"moderator": 1}
, which translates to array('moderator' => 1)
in php. You are comparing a boolean true
with an integer 1
using a type-safe comparison. That will fail because the types do not match. See http://php.net/manual/en/language.operators.comparison.php for more detail.
You can remedy this by either using type-unsafe comparisons or by converting your $permissions
to booleans.
if ((bool)$permissions[$key] === true) // Both are now of type boolean and will be compared.
or
if ($permissions[$key] == true) // Will compare 1 and TRUE, which will result in TRUE.
Upvotes: 3