Not getting the session user level

1

I am separating the menu according to the user level, but I can not get the level of the session.

Regardless of the user level it only shows the adm menu that is level 2

Where is the error?

Another thing how can I put more levels? type 1 for user, 2 for administrator, 3 for seller etc?

On each page I put the code below:

session_start();
$_SESSION['nivel'] = $nivel;    
if($nivel == 1 ){
    echo include 'adm/menu2.php';
    echo "<a href=''>Painel de Usuário</a>";

}else{
    echo include 'adm/menu.php';
    echo "<a href=''>Painel de Admin</a>";
}

The page that validates the login is like this:

<?php

// QUANDO TENTANDO LOGAR
if(isset($_POST['acesso'])=="Logar") {

// VERIFICANDO SE USUÁRIO E SENHA ESTÃO VAZIOS
    if(isset($_POST['usuario'])=="" || isset($_POST['senha'])=="") {
        echo "Os dados de acesso devem ser preenchidos";
        exit;
    }

// LOGANDO E CRIANDO AS SESSIONS
    $logar = mysqli_query($conexao,"SELECT usuario, senha, nivel FROM acesso WHERE usuario='".anti_injection($_POST['usuario'])."' AND senha='".anti_injection(md5($_POST['senha']))."' AND nivel='".anti_injection($nivel)."'");

    if(mysqli_num_rows($logar) >= 1) {
        $_SESSION['usua'] = $_POST['usuario'];
        $_SESSION['senh'] = md5($_POST['senha']);
        $_SESSION['nivel'] = $_POST['nivel'];
        echo "<script>
        alert('Acesso permitido');
        location.href='index.php';
        </script>";
    } else {
       echo "<script>
       alert('Acesso restrito');
       </script>";
    }

}

// VERIFICANDO SE O NÍVEL DA PÁGINA É VÁLIDA PARA O USUÁRIO LOGADO
if(@$_SESSION['usua'] AND @$_SESSION['senh'] AND @$_SESSION['nivel']) {
    $verifica_nivel = mysqli_query($conexao,"SELECT usuario, senha, nivel FROM acesso WHERE usuario='".anti_injection($_SESSION['usua'])."' AND senha='".anti_injection($_SESSION['senh'])."' AND nivel='".anti_injection($nivel)."'");

    if(mysqli_num_rows($verifica_nivel) >= 1) {
    // ACESSO CORRETO
    } else {
        echo "<script>
        alert('Você não tem o nível de acesso para essa página');
        history.back();
        </script>";
        exit;
    }
}

// CASO NÃO LOGADO, MOSTRA O FORMULÁRIO
if(!isset($_SESSION['usua']) OR !isset($_SESSION['senh']) OR $_SESSION['usua']=="" OR $_SESSION['senh']=="") {

?>

<?php
$qr=mysqli_query($conexao,"SELECT DISTINCT usuario, nivel FROM 'acesso' ORDER BY 'acesso'.'usuario' ASC");
if (mysqli_num_rows($qr)==0){
    echo "Adicione ao menos um Usuário";

}else{

}  
?>

<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/ie10-viewport-bug-workaround.css" rel="stylesheet">
<link href="css/signin.css" rel="stylesheet">

<form action="" method="post" form class="form-signin" >

<p align="center"> <img src="img/logo.png" border="0"></p>
<h2 class="form-signin-heading">Área Restrita</h2>
<label><p align="center"><font color="#000000"><font color="#FF0000"><b>Usuário : </label><select class="form-control" name="usuario">
   <option value="">Selecione o Usuário</option>
   <option value="Celia">Célia</option>
   <option value="Elin">Elin</option>
   <option value="Mariana">Mariana</option>
   <option value="Regiane">Regiane</option>
   <option value="Roberto">Roberto</option>
</div>
<BR>
<br />
<font color="#FF0000"><b>Senha :         </b></font> <input type="password" name="senha" class="form-control" value="">      <BR>
<br />
<input class="btn btn-lg btn-danger btn-block" type="submit" name="acesso" value="Acessar"></font></p>
</form>
<?php
    exit;
}
?>
    
asked by anonymous 06.05.2018 / 16:52

1 answer

0

You're setting $_SESSION to $nivel , not $nivel to $_SESSION , should look like this:

session_start();
$nivel = $_SESSION['nivel'];
if($nivel == 1 ){
    include 'adm/menu2.php';
    echo "<a href=''>Painel de Usuário</a>";
}elseif($nivel == 2 ){
    include 'adm/menu.php';
    echo "<a href=''>Painel de Admin</a>";
}elseif($nivel == 3 ){
    //aqui vai o menu para nível 3 e vai adicionando elseif() de acordo com a necessidade
}

If instead of else was a elseif() it would not print any menu as desired.

Edit your code:

// QUANDO TENTANDO LOGAR
if(isset($_POST['acesso'])=="Logar") {

    // VERIFICANDO SE USUÁRIO E SENHA ESTÃO VAZIOS
    if(isset($_POST['usuario'])=="" || isset($_POST['senha'])=="") {
        echo "Os dados de acesso devem ser preenchidos";
        exit;
    }

    // LOGANDO E CRIANDO AS SESSIONS
    $usuario=anti_injection($_POST['usuario']);
    $senha=anti_injection(md5($_POST['senha']));
    $logar = mysqli_query($conexao,"SELECT nivel FROM acesso WHERE usuario='$usuario' AND senha='$senha'");

    if(mysqli_num_rows($logar) >= 1) {
        while($result = mysqli_fetch_assoc($logar)){
            $_SESSION['nivel']=$result['nivel'];
        }
        $_SESSION['usua'] = $_POST['usuario'];
        $_SESSION['senh'] = md5($_POST['senha']);
        echo '
            <script type="text/javascript">
                alert("Acesso permitido");
                location.href="index.php";
            </script>
        ';
    } else {
        echo '
            <script type="text/javascript">
                alert("Acesso restrito");
            </script>
        ';
        //aqui você direciona o usuario para o cadastro
    }

}

There is no need to bring database "user and password", since you are already using WHERE for verification, the mysqli_num_rows() result account will only be 1 if WHERE conditions are% with%. The level was swallowed and saved in true , for later scans. Once the level session is saved, the pages that have restricted access can contain a% variable of% with its value, for example:

pagina1.php
session_start();
$resticao=2;//ou seja, apenas com nível 2 poderão acessar a pagina
if($_SESSION['nivel'] != $resticao){
    //redireciona o usuario porque não tem acesso, usando header();
}

Page printing will only be printed if the user has a sufficient level.

Another suggestion is to encrypt the password, avoid using $_SESSION , because the decryption is fast, that is, the security of this encryption is not high, use hashs like PHP or MD5() , preferably the SHA512 of SHA256 that creates a new hash password using a strong single-path hash algorithm.

  

Password_hash () documentation

ALTERNATIVE TO password_hash() Instead of using PHP , you can create a ELSEIF() :

switch($_SESSION['nivel']){
    case '1':
        //imprime o menu pro viel 1
        break;
    case '2':
        //imprime o menu pro viel 2
        break;
    case '3':
        //imprime o menu pro viel 3
        break;
    case '4':
        //imprime o menu pro viel 4
        break;
    // etc..
}

You can also use a logic based on the names of the menus, for example, if the level is just a single number, you can do something like this, without needing elseif() or switch() :

include 'adm/menu'.$_SESSION['nivel'].'.php';

So it will always call the exact level menu, as long as menu1 is referring to level 1, and so on.

    
06.05.2018 / 17:03