Hart Studio
Hart Studio

Reputation: 13

PHP function inside a if statements with logical operator

I have a page with limited permissions. Only 'amministratore' users can access to it and I would like to give the same permissions to 'dipendente' users.

Here is the working code of the controller:

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();
}   

I want also the 'dipendente' user to be able to access the page but if I add the logical operations it seems not to work:

if(!userHasRole('amministratore') || !userHasRole('dipendente')){ 
    $error = 'Solo gli utenti registrati possono accedere a quest\'area';
    include '../accessonegato.html.php'; 
    exit();
}   

Can someone tell me what I'm doing wrong?

Upvotes: 0

Views: 98

Answers (3)

Daniele Martini
Daniele Martini

Reputation: 143

You have to change the if statements logic, now it is:

((!userHasRole('amministratore') || !userHasRole('dipendente'))

it should be:

(!(userHasRole('amministratore') || userHasRole('dipendente'))

Upvotes: 0

B. Fleming
B. Fleming

Reputation: 7220

What you want to do is provide an error "if the user isn't an amministratore or a dipendente". This can be written as if(!(userHasRole('amministratore') || userHasRole('dipendente')). If we distribute the negation according to De Morgan's laws, this can be rewritten as if(!userHasRole('amministratore') && !userHasRole('dipendente')).

Whenever you distribute negation, you switch from && to || or vice versa.

Upvotes: 1

KIKO Software
KIKO Software

Reputation: 16688

Instead of

  if (!userHasRole('amministratore') || !userHasRole('dipendente')) {

use

 if (!(userHasRole('amministratore') || userHasRole('dipendente'))) {

It's basically the same as checking one role, but now you're doing two.

Upvotes: 0

Related Questions