我试图做一个验证级别函数使用在我的页面顶部,以控制访问每个页面取决于管理员的级别。
我现在做这个函数是为了这个目的:
function verifyLevel($userId){
$pdo = start();
$read = $pdo->prepare("SELECT * FROM admins where id = :userId");
$read->bindValue(":userId", $userId);
$read->execute();
$result = $read->fetch(PDO::FETCH_ASSOC);
echo $result['level'];
}
现在我正在尝试使用这个函数。
管理员级别为1、2或3。
在这个页面中,我想允许1级和3级的用户可以看到内容。
只有2级管理员才能看到这个页面的内容,我想显示一条消息,说他们没有权限的管理员2级
我想这样做:
if(function_exists('verifyLevel')){
if(verifyLevel($_SESSION['admin']['id'] == '2')){
echo 'Sorry, but you dont have permissions to acess this page.';
}
else{
//I show page content
}
}
但是它不工作,所有级别都可以访问这个页面的内容。
你看到我的错误在哪里了吗?
您正在回显verifyLevel()
的结果,您需要返回它以使其具有可比性:
function verifyLevel($userId){
// ...
return $result['level'];
}
// bracket in wrong place -----------V--not--v
if(verifyLevel($_SESSION['admin']['id']) == '2') {
echo 'Sorry, but you dont have permissions to acess this page.';
}
正如Jeremy Miller所提到的,您设置函数调用的方式,它将传递一个布尔值为true或false,这大致相当于0或1,因此您的用户可能不会从数据库中正确返回:
// incorrect comparison here, passing boolean instead (0 or 1)
var_dump(verifyLevel($_SESSION['admin']['id'] == '2'));
应:// true representation of your function's processing and comparison
var_dump(verifyLevel($_SESSION['admin']['id']) == '2');
// verifyLevel($_SESSION['admin']['id']) will either be 1, 2 or 3