I can’t login after I enter the user’s email and password

Asked

Viewed 95 times

3

I made a login system, only that does not enter the system where always returns to the home screen and does not enter the conditional I want, I think this is happening in the file valida_login.php.

There are the following files where just below are in order:

  • Filing cabinet php connection. (Connection to the database)
  • Filing cabinet login.php (Main screen of login)
  • Filing cabinet valida_login.php (Checks if the user is registered in the system, the error is here, because it always falls in the condition of returning the login screen)
  • Filing cabinet classe_usuario.php (Has the Logar method())
  • Filing cabinet hi php. (After the email and password are valid, this page should be released to the user)
// Arquivo conexão
<?php

    session_start(); // Necessário o uso de sessão

    global $conexao; // Variavél global criada para ser usada em qualquer parte do sistema
    // Variavéis para conexão
    $host = 'localhost';  
    $banco = 'web';
    $usuario = 'root';
    $senha = '';

    // Se for possível a conexão
    try {

        // PDO é extensão do PHP para conectar com o banco
        $conexao = new PDO("mysql:host=$host;dbname=$banco",$usuario,$senha);
        $conexao->setAttribute(PDO::ATTR_ERRMODE, PDO::ATTR_EXCEPTION);

    // Se a conexão não for possível
    } catch (PDOException $falha_conexao) {
        echo "Erro na conexão do banco".$falha_conexao->getMessage();
    } catch (Exception $falha) {
        echo "Erro não proveniente a conexão do banco".$falha->getMessage();
    }
?>
// Tela login.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <title> Login </title>
</head>
<body>
    <h1> Bem vindo ao sistema </h1>
    <form method="POST" action="../Login/valida_login.php">
        <p> Email: <input type="email" name="login" placeholder="Digite seu email" size=30 
            required maxlength="50"> </p>
        <p> Senha: <input type="password" name="senha" placeholder="Digite a sua senha" size=30 
            required maxlength="32"> </p>
        <p> <input type="submit" name="Entrar" value="Entrar"> </p>
        <p> Esqueceu sua senha? <a href="../Login/redefinir_senha.php"> Clique aqui para redefini-la</a> </p>
    </form>
</body>
</html>
// Tela valida_login.php
<?php
    // Se existir o botão Entrar
    if(isset($_POST['Entrar'])){
        // Se existirem os parâmetros e não forem ambos vazios 
        if(isset($_POST['email']) && !empty($_POST['email']) 
        && isset($_POST['senha']) && !empty($_POST['senha'])){
            // Importando conexão
            require_once '../Login/conexao.php';
            // Importando a classe Usuario
            require_once '../Login/usuarios.php';
            // Criando uma instância da classe Usuario
            $u = new Usuario();
            // Valida as informações com segurança contra pessoas mal intencionadas
            $email = addslashes($_POST['email']);
            $senha = addslashes($_POST['senha']);
            // Verifica o método
            if($u->Logar($email,$senha) == true){
                // Se existir a $_SESSION['id_usuario']
                if (isset($_SESSION['id_funcionario'])){
                    // Será redirecionado para a tela principal
                    header("Location: ../Login/oi.php");
                }else{
                    // Será redirecionado para a tela de login
                    header("Location: ../Login/login.php");
                }
            }
            // Se não, será redirecionado para a tela de login
        }else{
            header("Location: ../Login/login.php.php");
        }   
    } 
?>
<?php
// Tela classe_usuario.php  
    // Classe usuário
    class Usuario{
        // Método Logar
        public function Logar($email,$senha){
            // Recebe a variável global
            global $conexao;
            // Verifica se o funcionário existe no banco
            $login = "SELECT * FROM funcionario WHERE email = :email AND senha = :senha";
            // Prepara a conexão com o banco
            $login = $conexao->prepare($login);
            // Vincula um valor a um parâmetro
            $login->bindValue(':email',$email);
            $login->bindValue(':senha',md5($senha));
            // Executa a operação
            $login->execute();
            // Condição que retorna o cd_funcionario (se houver)
            if($login->rowCount() > 0){
                // Retorna o array dos dados
                $dado = $login->fetch();
                // Variável global da sessão armazena a variável cd_funcionario
                $_SESSION['id_funcionario'] = $dado['cd_funcionario'];
                // Login feito
                return true;
            // Se não
            }else{
                // Login não feito
                return false;
            }
        }
    }
?>
// Tela oi.php
<?php
    // Importa a conexão
    require_once '../Login/conexao.php';

    // Mensagem de teste
    echo "Seja bem vindo";

    // Se existir sair
    if(isset($_GET['sair'])){
        // Destrói todos os dados associados com a sessão atual
        session_destroy();
        // Retorna a tela de login
        header('Location: login.php');
        die(); // Saída
    }
?>

<p><a href="login.php" name="sair">Sair</a></p>
  • Check your server logs to make sure no errors occurred while running.

  • The connection to the bank works

  • Are the names of the posted files the same as the ones you have in the application? Because the name of the file that contains the class Usuario is called classe_usuario.php, but in your code you refer to it as php users.

  • @Tiagoa isn’t that yet, I’ve changed but it hasn’t helped.

1 answer

3


The problem is that in the form the field entitled "E-mail" is with name login and in php you are expecting a key email in the $_POST:

Of:

<p> Email: <input type="email" name="login" placeholder="Digite seu email" size=30 
            required maxlength="50"> </p>

To:

<p> Email: <input type="email" name="email" placeholder="Digite seu email" size=30 
            required maxlength="50"> </p>
  • The error is self-explanatory: the constant ATTR_EXCEPTION does not exist, see: https://www.php.net/manual/en/class.pdo.php

  • It worked, I don’t believe the mistake was that, thank you very much. I took the $conexao->setAttribute(PDO::ATTR_ERRMODE, PDO::ATTR_EXCEPTION); of the archive conexao.php because I was making a mistake.

  • I’m having trouble with the logout, i wanted the user not to enter the index so as not to bypass the login system or to go back to the page so as not to enter the session without entering the email and password, but I can not post on Stake Overflow for now.

  • Just validate the session on every page you want to protect, for example, you create a file called protect.php in it you make a check if the session exists and if the key id_funcionario is filled in, if not, redirect to the login screen with the header("Location: ../Login/login.php");.

  • I wanted to do it inside the page oi.php, I’ll update the code oi.php for you to see what I’ve done.

  • Have you update your answer by putting the solution of logout page oi.php?

Show 1 more comment

Browser other questions tagged

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