[英]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.