[英]PHP function inside a if statements with logical operator
我的页面权限有限。 只有'amministratore'
用户可以访问它,我想为'dipendente'
用户赋予相同的权限。
这是控制器的工作代码:
function userHasRole($role) {
include 'db.inc.php';
try
{
$sql = "SELECT COUNT(*) FROM utenti
INNER JOIN utentiruoli ON utenti.id = utenteid
INNER JOIN ruoli ON ruoloid = ruoli.id
WHERE mail = :mail AND ruoli.id = :ruoloid";
$s = $pdo->prepare($sql);
$s->bindValue(':mail', $_SESSION['mail']);
$s->bindValue(':ruoloid', $role);
$s->execute();
} catch (PDOException $e) {
$error = 'Errore nella ricarca del ruolo utente.';
include 'error.html.php';
exit();
}
$row = $s->fetch();
if ($row[0] > 0) {
return TRUE;
} else {
return FALSE;
}
}
exit();
}
if(!userHasRole('amministratore')){
$error = 'Solo gli utenti registrati possono accedere a quest\'area';
include '../accessonegato.html.php';
exit();
}
我也希望'dipendente'
用户能够访问该页面,但是如果我添加逻辑操作,它似乎将不起作用:
if(!userHasRole('amministratore') || !userHasRole('dipendente')){
$error = 'Solo gli utenti registrati possono accedere a quest\'area';
include '../accessonegato.html.php';
exit();
}
有人可以告诉我我在做什么错吗?
您要执行的操作是提供一个错误消息“如果用户不是管理员或二等兵”。 这可以写成if(!(userHasRole('amministratore') || userHasRole('dipendente'))
。如果我们根据De Morgan的定律分配否定,则可以重写为if(!userHasRole('amministratore') && !userHasRole('dipendente'))
。
每当您分发否定词时,便从&&
切换到||
或相反亦然。
代替
if (!userHasRole('amministratore') || !userHasRole('dipendente')) {
采用
if (!(userHasRole('amministratore') || userHasRole('dipendente'))) {
它基本上与检查一个角色相同,但是现在您要执行两个角色。
您必须更改if语句逻辑,现在是:
((!userHasRole('amministratore')||!userHasRole('dipendente'))
它应该是:
(!(userHasRole('amministratore')|| userHasRole('dipendente'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.