Login with permission levels

Asked

Viewed 1,077 times

3

I have a login system that, if the user is an administrator, will be redirected to one page and if common, to another.

That column ativo is what defines whether a user is admin(1) or not(0).

identifiant  |  senha  |  ativo 
aaaaaaaaaaaa    12345       1
bbbbbbbbbbbb    12345       0

The login page:

<!--A parte do formulário-->
<?php session_start(); ?>
    <div class="container">
        <div class="row">
            <div class="col-md-4 col-md-offset-4">
                <div class="login-panel panel panel-default">
                    <div class="panel-heading" style="
    margin-top: 14px;">
                        <h3 class="panel-title">Login</h3>
                    </div>
                    <div class="panel-body" style="background: rgba(32, 40, 76, 0.59);">
                        <?php 
                        if(isset($erro)) 
                            if(count($erro) > 0){ ?>
                                <div class="alert alert-danger">
                                    <?php foreach($erro as $msg) echo "$msg <br>"; ?>
                                </div>
                            <?php 
                            }
                            ?>
                        <form method="post" action="validacao.php" role="form">
                            <fieldset style="background: #9498a9;">
                                <div class="form-group">
                                    <input  class="form-control" placeholder="Identifiant" name="identifiant">
                                </div>
                                <div class="form-group">
                                    <input class="form-control" required placeholder="Senha" name="senha" type="password" value="">
                                </div>
                                <div class="checkbox">
                                    <label>
                                        <input name="remember" type="checkbox" value="Remember Me">Lembrar-me
                                    </label>
                                </div>

                                <button type="submit" name="login" value="true" class="btn btn-success btn-block" style="background: #232b4f; border-color: #e2e2e2;">Login</button>
                            </fieldset>
                        </form>
                        <p class="text-center text-danger">
                                <?php if(isset($_SESSION['loginErro'])){
                                        echo $_SESSION['loginErro'];
                                        unset($_SESSION['loginErro']);
                                }?>
                        </p>
                        <p class="text-center text-success">
                                <?php 
                                if(isset($_SESSION['logindeslogado'])){
                                        echo $_SESSION['logindeslogado'];
                                        unset($_SESSION['logindeslogado']);
                                }
                                ?>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>

The validation page:

<?php
    session_start();    
    //Incluindo a conexão com banco de dados
    include_once("conexao.php");    
    //O campo usuário e senha preenchido entra no if para validar
    if((isset($_POST['identifiant'])) && (isset($_POST['senha']))){
        $usuario = mysqli_real_escape_string($conn, $_POST['identifiant']); //Escapar de caracteres especiais, como aspas, prevenindo SQL injection
        $senha = mysqli_real_escape_string($conn, $_POST['senha']);

        //Buscar na tabela usuario o usuário que corresponde com os dados digitado no formulário
        $result_usuario = "SELECT * FROM usuarios WHERE identifiant = '$identifiant' and senha = '$senha' LIMIT 1";
        $resultado_usuario = mysqli_query($conn, $result_usuario);
        $resultado = mysqli_fetch_assoc($resultado_usuario);

        //Encontrado um usuario na tabela usuário com os mesmos dados digitado no formulário
        if(isset($resultado)){
            $_SESSION['id'] = $resultado['id'];
            $_SESSION['ativo'] = $resultado['ativo'];
            $_SESSION['identifiant'] = $resultado['identifiant'];
                if($_SESSION['ativo'] == "1"){
                    header("Location: principal.php");
                }elseif($_SESSION['ativo'] == "0"){
                    header("Location: principalUSU.php");
                }
        //Não foi encontrado um usuario na tabela usuário com os mesmos dados digitado no formulário
        //redireciona o usuario para a página de login
        }else{  
            //Váriavel global recebendo a mensagem de erro
            $_SESSION['loginErro'] = "Usuário ou senha Inválido";
            header("Location: login.php");
        }
    //O campo usuário e senha não preenchido entra no else e redireciona o usuário para a página de login
    }else{
        $_SESSION['loginErro'] = "Usuário ou senha inválido";
        header("Location: login.php");
    }
?>

The big problem is that even if you enter the right login and password, it says that login or password are invalid and redirects you to the login page.

NOTE: This question looks like one I asked, but the code is another, I preferred not to edit that question because here the code is structured in a different way and I didn’t want to lose the previous code.

  • 2

    You are mixing "MYSQLI API" with "MYSQL API". This will give problem. In the other question the code although using both Apis they are in different files and there probably works, the code here no longer has to work, I recommend that it stays in the other one that at least is not a "typo".

1 answer

3

login.php

        <?php
                session_start();
        ?>
        <!DOCTYPE html>
        <html lang="pt-br">
          <head>
            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
            <meta name="description" content="">
            <meta name="author" content="Cesar Szpak">
            <link rel="icon" href="imagens/favicon.ico">

            <title>Login</title>

            <!-- Bootstrap core CSS -->
            <link href="css/bootstrap.css" rel="stylesheet">

            <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
            <link href="css/ie10-viewport-bug-workaround.css" rel="stylesheet">

            <!-- Custom styles for this template -->
            <link href="css/signin.css" rel="stylesheet">

            <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
            <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
            <script src="js/ie-emulation-modes-warning.js"></script>

            <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
            <!--[if lt IE 9]>
              <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
              <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
            <![endif]-->
          </head>

          <body>

            <div class="container">

              <form class="form-signin" method="POST" action="valida.php">
                <h2 class="form-signin-heading">Área Restrita</h2>
                <label for="inputEmail" class="sr-only">Email</label>
                <input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email" required autofocus>
                <label for="inputPassword" class="sr-only">Senha</label>
                <input type="password" name="senha" id="inputPassword" class="form-control" placeholder="Senha" required>
                <button class="btn btn-lg btn-danger btn-block" type="submit">Acessar</button>
              </form>
                  <p class="text-center text-danger">
                                <?php if(isset($_SESSION['loginErro'])){
                                        echo $_SESSION['loginErro'];
                                        unset($_SESSION['loginErro']);
                                }?>
                        </p>
                        <p class="text-center text-success">
                                <?php 
                                if(isset($_SESSION['logindeslogado'])){
                                        echo $_SESSION['logindeslogado'];
                                        unset($_SESSION['logindeslogado']);
                                }
                                ?>
                        </p>
            </div> <!-- /container -->


            <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
            <script src="js/ie10-viewport-bug-workaround.js"></script>
          </body>
        </html>

valida.php

    <?php
            session_start();    
            //Incluindo a conexão com banco de dados
            include_once("conexao.php");    
            //O campo usuário e senha preenchido entra no if para validar
            if((isset($_POST['email'])) && (isset($_POST['senha']))){
                    $usuario = mysqli_real_escape_string($conn, $_POST['email']); //Escapar de caracteres especiais, como aspas, prevenindo SQL injection
                    $senha = mysqli_real_escape_string($conn, $_POST['senha']);
                    $senha = md5($senha);

                    //Buscar na tabela usuario o usuário que corresponde com os dados digitado no formulário
                    $result_usuario = "SELECT * FROM usuarios WHERE email = '$usuario' and senha = '$senha' LIMIT 1";
                    $resultado_usuario = mysqli_query($conn, $result_usuario);
                    $resultado = mysqli_fetch_assoc($resultado_usuario);

                    //Encontrado um usuario na tabela usuário com os mesmos dados digitado no formulário
                    if(isset($resultado)){
                            $_SESSION['usuarioId'] = $resultado['id'];
                            $_SESSION['usuarioNome'] = $resultado['nome'];
                            $_SESSION['usuarioNiveisAcessoId'] = $resultado['niveis_acesso_id'];
                            $_SESSION['usuarioEmail'] = $resultado['email'];
                            if($_SESSION['usuarioNiveisAcessoId'] == "1"){
                                    header("Location: administrativo.php");
                            }elseif($_SESSION['usuarioNiveisAcessoId'] == "2"){
                                    header("Location: colaborador.php");
                            }else{
                                    header("Location: cliente.php");
                            }
                    //Não foi encontrado um usuario na tabela usuário com os mesmos dados digitado no formulário
                    //redireciona o usuario para a página de login
                    }else{  
                            //Váriavel global recebendo a mensagem de erro
                            $_SESSION['loginErro'] = "Usuário ou senha Inválido";
                            header("Location: index.php");
                    }
            //O campo usuário e senha não preenchido entra no else e redireciona o usuário para a página de login
            }else{
                    $_SESSION['loginErro'] = "Usuário ou senha inválido";
                    header("Location: index.php");
            }
    ?>

quit php.

<?php
    session_start();

    unset(
        $_SESSION['usuarioId'],
        $_SESSION['usuarioNome'],
        $_SESSION['usuarioNiveisAcessoId'],
        $_SESSION['usuarioEmail'],
        $_SESSION['usuarioSenha']
    );

    $_SESSION['logindeslogado'] = "Deslogado com sucesso";
    //redirecionar o usuario para a página de login
    header("Location: index.php");
?>

Browser other questions tagged

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