Hart Studio Hart Studio - 3 years ago 194
PHP Question

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download