Login without selecting level

Asked

Viewed 42 times

1

I am making a PHP site for my TCC, and one of the guidelines given was to remove the level selection, and that this was done automatically by the system. My teacher said it was just to remove the select code, but if I do it nothing happens. Follow below the HTML and PHP codes

<form id="form2" name="form2" method="post" action="php/usuarioautenticado.php">

            <input type="text" name="username" id="username" required="required" placeholder="Usuário"/>

            <input type="password" name="senha" id="senha" required="required" placeholder="Senha"/>

            <select name="nivel" form="form2" class="select">
                <option value="">Escolha seu nível</option>
                <option value="admin">Administrador</option>
                <option value="usuario">Usuário</option>
            </select>

            <input type="submit" name="enviar" id="enviar" value="Enviar" />

<?php // Código para verificação no banco do login e senha
   if (isset ($_POST ['enviar'])){// se o campo enter for clicado

       $username=$_POST['username'];
       $senha=$_POST['senha'];
       $nivel=$_POST['nivel'];

       $query = @mysql_query ("SELECT * FROM cadastro WHERE username='$username' AND senha ='$senha' AND nivel='$nivel'"); // Verifique no banco se o login e a senha digitados existem.
       $conta = @mysql_num_rows ($query);// conte os dados do banco selecionados na variável query

       if ($conta == '0') {// se o valor digitado não existir 

            echo "<script language= 'javascript'> window.alert('Os campos  não correspondem');</script>"; 

            header ("LOCATION: ../index.php");


        }else{

            while ($resultado= @mysql_fetch_array($query) ){// estamos verificando os dados do banco em uma lista ( array )

        $id = $resultado ['id']; 
        $username= $resultado ['username'];
        $senha = $resultado ['senha'];
        $nivel = $resultado ['nivel'];

       // vamos abrir a sessão pois para que possamos manipular páginas com nivel é preciso abrir a sessão para manter os dados abertos e também deve ter um botão de sair para destruir a sessão. 

       session_start ();
       $_SESSION['id'] = $id;
        $_SESSION['username'] = $username;
        $_SESSION['senha'] = $senha;
       $_SESSION['nivel'] = $nivel;

       // redirecionar para página correta

       if ($nivel == 'admin'){ 

     header ("LOCATION: select.php");

       }elseif ($nivel =='usuario'){

     header ("LOCATION: mostradados.php");

       }else{

        return false;

       }

        }}
   }

   ?>
  • Have you tried removing the AND nivel='$nivel' in query?

  • Yeah, I tried a couple of times and it wasn’t.

  • Click on [Edit] and posted as you are currently doing.

  • What do you mean? I’m sorry, I’m new here, I don’t really know how the site works :/

1 answer

0

Hello, you are using 2 equal users with different profiles?
Follow how I log into my systems:

Table

CREATE TABLE USUARIO -- CADASTRO: SU
(
ID INT PRIMARY KEY AUTO_INCREMENT,
EMAIL VARCHAR(100),
SENHA VARCHAR(100),
STATU INT, -- ATIVO / INATIVO
ACESSO VARCHAR(3), -- PRO, CAX, USU
SUU INT, -- SUPER USUARIO
DATA_CADASTRO DATETIME,
DATE_UPDATE DATETIME
);



Form

<form class="form-horizontal m-t-20" id="loginform" method="post">
                    <div class="row p-b-30">
                        <div class="col-12">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text bg-success text-white" id="basic-addon1"><i class="ti-user"></i></span>
                                </div>
                                <input type="email" name="txtEmail" class="form-control form-control-lg" placeholder="Email" aria-label="Username" aria-describedby="basic-addon1" required="">
                            </div>
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <span class="input-group-text bg-warning text-white" id="basic-addon2"><i class="ti-pencil"></i></span>
                                </div>
                                <input type="password" name="txtSenha" class="form-control form-control-lg" placeholder="Senha" aria-label="Password" aria-describedby="basic-addon1" required="">
                            </div>
                        </div>
                    </div>
                    <div class="row border-top border-secondary">
                        <div class="col-12">
                            <div class="form-group">
                                <div class="p-t-20">
                                <br>
                                    <button class="btn btn-info" id="to-recover" type="button"><i class="fa fa-lock m-r-5"></i> Esqueceu a Senha?</button>
                                    <button class="btn btn-success float-right" name="btnEntrar" type="submit">Entrar</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>



Page post

if (isset($_POST["btnEntrar"])) {
                                echo "<script>document.getElementById('btnEntrar').disabled=true;</script>";
                                if (!isset($_SESSION["NUMTENTATIVAS"])) {
                                    $_SESSION["NUMTENTATIVAS"] = 0;
                                }
                                if ($_SESSION["NUMTENTATIVAS"] >= 5) {
                                    echo "<script>document.getElementById('btnEntrar').disabled=false;</script>";
                                    echo "<script> $(function(){
        toastr.warning('Você está temporariamente bloqueado, aguarde alguns minutos e tente novamente ou clique em Esqueceu a Senha para enviar um email!', 'Atenção!');
    });
            </script>";
                                } else {
                                    require_once 'DAO/UsuarioDAO.php';
                                    $u = new UsuarioDAO();
                                    $u->EMAIL = trim($_POST["txtEmail"]);
                                    $u->SENHA = md5($_POST["txtSenha"]);
                                    $msg = $u->EfetuarLogin();
                                    if($msg == "OK") {
                                        echo "<script> $(function(){
        toastr.success('Carregando...', 'Sucesso!');
    });
            </script>";
                                        $_SESSION["EMAIL"] = $u->EMAIL;
                                        $_SESSION["ID"] = $u->ID;
                                        $_SESSION["TIPO"] = $u->ACESSO;
                                        $_SESSION["SU"] = $u->SUU;

                                        LogDAO::InsertLog("Login", "Entrou", "Entrou no Sistema", $_SESSION["EMAIL"], __ROOT__."/web");
                                        echo "<script>location.href='".$link."/Painel';</script>";
                                    } else {
                                        echo "<script>document.getElementById('btnEntrar').disabled=false;</script>";
                                        $erro = true;
                                    }
                                        if($erro){
                                            $_SESSION["NUMTENTATIVAS"] = $_SESSION["NUMTENTATIVAS"] + 1;
                                            LogDAO::InsertLog("Login", "Erro", "Tentativa ".$_SESSION["NUMTENTATIVAS"]." de Login - ".$msg, $u->EMAIL, __ROOT__."/web");
                                            echo "<script> $(function(){
        toastr.error('".$msg."', 'Erro!');
    });
            </script>";
                                        }
                                    }
                                }



User Class

function EfetuarLogin(){
    $this->ErroCode = 0;
    $this->ErroMsg = "";
    require_once "Conexao/conexao.php";
    $c = new conexao();
    try{
        $c->Abrir();
        $SQL = "SELECT ID, STATU, ACESSO, SUU FROM USUARIO WHERE EMAIL = '".$this->EMAIL."' AND SENHA = '".$this->SENHA."'";
        $c->ExecQuery($SQL);
        while($eqp = $c->FetchArray()){
            $this->ErroCode = 0;
            $this->ErroMsg = "OK!";
            $this->ID = $eqp["ID"];
            $this->ACESSO = $eqp["ACESSO"];
            $this->SUU = $eqp["SUU"];

            if($eqp["STATU"] == 0) {
                $this->ErroCode = 1;
                $this->ErroMsg = "Usuário Inativo!";
            }
        }

        if($this->ErroMsg == ""){
            $this->ErroMsg = "Email ou Senha Incorretos!";
        }

        if($this->ErroMsg == "OK!"){
            return "OK";
        } else {
            return $this->ErroMsg;
        }
    }catch (Exception $e){
        $this->ErroCode = 1;
        $this->ErroMsg = "Erro ao Efetuar Login - ".$e->getMessage();
        return $this->ErroMsg;
    }//finally{
    $c->Fechar();
    //}
}



I also create a screen for managing users where the administrator can change the access of each one.
I hope it helps :)

Browser other questions tagged

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