Not getting user level from Session

Asked

Viewed 145 times

1

I am separating the menu according to the user’s level, but I can’t get the level of the Session.

Regardless of the user level it only shows the Adm menu which 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 Cód 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;
}
?>
  • That doesn’t make sense: isset($_POST['acesso'])=="Logar" - The result of isset is true or false, will never be "Log in". What you can do, eventually, is this: isset($_POST['acesso']) && $_POST['acesso']=="Logar". - First check if it is set, && then check if it is "Log in".

1 answer

0

You are defining the $_SESSION like the $nivel, and not the $nivel as the $_SESSION, it should be 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 in place of else were a elseif() would not print any menu as desired.

Edit of 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
    }

}

No need to bring "user and password" from the database once you are already using WHERE for verification, the profit and loss account mysqli_num_rows() will only be 1 if the conditions of WHERE were true. The level was brought and saved in a $_SESSION, for further checks. Once the level session is saved, pages that have restricted access may contain a variable PHP 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 sufficient level.

Another suggestion is password encryption, avoid using MD5(), because decryption is fast, that is, the security of this encryption is not high, use hashs like SHA512 or SHA256, preferably the function password_hash() of PHP which creates a new password hash using a strong single track hash algorithm.

Documentation of password_hash()

ALTERNATIVE TO THE ELSEIF() Instead of using elseif(), you can create a switch():

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 menu names, for example, if the level is only a single number, da para fazer algo assim, no need to switch() or if():

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

So it will always call the exact level menu, provided that the menu1 is related to level 1, and so on.

  • 1

    Wees tried so too and it does not take the level and keeps showing only the Admin panel for all levels.

  • 1

    I saw that there are some strange things, like:

  • 1

    in the first query you use $nivel and the other variables $_POST then in the definition of $_SESSION['nivel'] you use $_POST['nivel'], but it wouldn’t be $nivel, since it is so in query?

  • Because instead of doing all this, you just don’t check the user and password, and if there exists you bring the level of the database and use it to set the menu?

  • 1

    and how do I do that?

  • 1

    I’ll rewrite your code

  • 1

    Thanks...I’m new to learning these things now

  • 1

    the other querys in my view are not necessary, in the part where vc shows the form, vc can only direct the user to the registration page, without the need for another query

  • take a look there, edited my answer

  • 1

    valeu Wees...now it worked out he is directing to the correct menu...now how can I put other levels...the way it is he sees if the user level is 1 and shows the menu.php and if it is different it shows the menu2.php, i have a 3rd level so it would have to be so level 1 shows menu.php level 2 shows mentu2.php level 3 shows menu3.php and so on.

  • 1

    I’ll edit it again then

  • 1

    What is this to be anti_injection in your code? Gives the impression of home function (usually this is bad sign). Can give more details?

  • 1

    Wees sorry I don’t respond fast is that came home visit.. kkk, but thank you so much for the help worked right...now I just need to lock the pages so that they are accessed by each level avoiding that it is accessed directly by the url

  • Quiet @Robert, anything just comment here or log in there in the chat if I can help.

Show 10 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.