PHP and Mysql Login Validation Problem

Asked

Viewed 101 times

1

I’m a beginner in PHP and I have a problem validating a login with access level.

Code Index.php

<?php
//Inicializado primeira a sessão para posteriormente recuperar valores das variáveis globais. 
session_start();
?>
<!doctype html>
<html lang="pt">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400&display=swap" rel="stylesheet">

    <link rel="stylesheet" href="fonts/icomoon/style.css">

    <link rel="stylesheet" href="css/owl.carousel.min.css">

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

    <!-- Style -->
    <link rel="stylesheet" href="css/style.css">

    <title>Astral Mistico</title>
</head>

<body>
    <div class="content">
        <div class="container">
            <div class="row justify-content-center">
                <!-- <div class="col-md-6 order-md-2">
      <img src="images/undraw_file_sync_ot38.svg" alt="Image" class="img-fluid">
    </div> -->
                <div class="col-md-6 contents">
                    <div class="row justify-content-center">
                        <div class="col-md-12">
                            <div class="form-block">
                                <div class="mb-4">
                                    <h3>Clube <strong>Astral Mistico</strong></h3>
                                    <p class="mb-4">Bem Vindo ao Clube Astral Mistico a maior plataforma de prestação de serviços holisticos e vendas de produtos faça seu login para começar</p>
                                </div>
                                <form action="login.php" method="POST">
                                    <div class="form-group first">
                                        <label for="usuario">Usuario</label>
                                        <input type="text" class="form-control" style="color: white;" name="usuario" id="usuario">

                                    </div>
                                    <div class="form-group last mb-4">
                                        <label for="senha">Senha</label>
                                        <input type="password" class="form-control" style="color: white;" name="senha" id="senha">

                                    </div>

                                    <div class="d-flex mb-5 align-items-center">
                                        <label class="control control--checkbox mb-0"><span class="caption">Lembrar de mim</span>
                  <input type="checkbox" checked="checked"/>
                  <div class="control__indicator"></div>
                </label>
                                        <span class="ml-auto"><a href="#" class="forgot-pass">Esqueceu sua Senha</a></span>
                                    </div>

                                    <input type="submit" value="Log In" class="btn btn-pill text-white btn-block btn-primary">
                                    <input type="button" value="Cadastre-se" onClick="Cadastro()" class="btn btn-pill text-white btn-block btn-primary">


                                    <span class="text-white d-block text-center my-4 "> ou faça login com:</span>

                                    <div class="social-login text-center ">
                                        <a href="# " class="facebook ">
                                            <span class="icon-facebook mr-3 "></span>
                                        </a>
                                        <a href="# " class="twitter ">
                                            <span class="icon-twitter mr-3 "></span>
                                        </a>
                                        <a href="# " class="google ">
                                            <span class="icon-google mr-3 "></span>
                                        </a>
                                            <p>
                                                <?php 
                                                //Recuperando o valor da variável global, os erro de login.
                                                if(isset($_SESSION['loginErro'])){
                                                    echo $_SESSION['loginErro'];
                                                    unset($_SESSION['loginErro']);
                                                }
                                                ?>
                                            </p>

                                            <p>
                                                <?php 
                                                //Recuperando o valor da variável global, deslogado com sucesso.
                                                if(isset($_SESSION['logindeslogado'])){
                                                    echo $_SESSION['logindeslogado'];
                                                    unset($_SESSION['logindeslogado']);
                                                }
                                                ?>
                                            </p>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                </div>

            </div>
        </div>
    </div>

    <script src="js/jquery-3.3.1.min.js "></script>
    <script src="js/popper.min.js "></script>
    <script src="js/bootstrap.min.js "></script>
    <script src="js/main.js "></script>
</body>

</html>

Code login.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['usuario'])) && (isset($_POST['senha']))){
    $usuario = mysqli_real_escape_string($conn, $_POST['usuario']); //Escapar de caracteres especiais, como aspas, prevenindo SQL injection
    $senha = mysqli_real_escape_string($conn, $_POST['senha']);
    $senha = md5($senha);
        
    //Buscar na tabela usuarios o usuário que corresponde com os dados digitado no formulário
    $sql = "SELECT usuario, senha, tipo_conta FROM usuarios";
    $resultado = mysqli_query($conn, $sql);
    
    //Encontrado um usuario na tabela usuarios com os mesmos dados digitado no formulário
    if (mysqli_num_rows($result) > 0)
        $_SESSION['usuario'] = $usuario;
        $_SESSION['senha'] = $senha;
        $_SESSION['tipo_conta'] = $tipo_conta;
        if($_SESSION['tipo_conta'] == "0"){
            header("Location: consulente.php");
        }elseif($_SESSION['tipo_conta'] == "1"){
            header("Location: prestador.php");
        }else{ 
            //Não foi encontrado um usuario na tabela usuarios com os mesmos dados digitado no formulário
            //redireciona o usuario para a página de login
            //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");
}
?>

connection to BD

<?php
$servidor = "127.0.0.1";
$usuario = "root";
$senha = "";
$dbname = "auth_users";    
//Criar a conexao
$conn = mysqli_connect($servidor, $usuario, $senha, $dbname);

if(!$conn){
 die("Falha na conexao: " . mysqli_connect_error());
 }else{
 echo "Conexao realizada com sucesso";
 }      
 ?>

The code returns incorrect user and password with any input, I am not able to process the data and log it into the specific accounts. Follow database structure below: https://drive.google.com/file/d/1kqBJ-l8IzyXYDAgfCYovO5HdCvse2Rqn/view?usp=sharing

Show 1 more comment

1 answer

1


Try using the following form of connection to test:

<?php 
session_start();
include("conexao.php");

$usuario = $_POST['usuario'];
$senha = $_POST['senha'];

$senha = md5($senha);

$selec = mysqli_query($conexao, "SELECT usuario, senha, tipo_conta FROM usuarios where usuario= '$usuario' and senha= '$senha'");
if ($dado = mysqli_fetch_array($selec)) {    
    
    $_SESSION['usuario'] = $usuario;
    $_SESSION['senha'] = $senha;        
    $_SESSION['tipo_conta'] = $dado['tipo_conta']; 

    if($_SESSION['tipo_conta'] == "0")
        header("Location: consulente.php");
    if($_SESSION['tipo_conta'] == "1")
         header("Location: prestador.php");
}else{
    $_SESSION['loginErro'] = "Usuário ou senha Inválido";
            header("Location: index.php");    
}

?>

php connection.

    <?php
    $conexao = mysqli_connect("localhost", "root", "", "auth_users");

    if (!$conexao) {
        echo "problema ao se conectar";
    }else{
        
    }
?>
  • Successful connection Notice: Undefined variable: connection in C: xampp htdocs Astral_mistico login.php on line 11 Warning: mysqli_query() expects Parameter 1 to be mysqli, null Given in C: xampp htdocs Astral_mistico login.php on line 11 Warning: mysqli_fetch_array() expects Parameter 1 to be mysqli_result, null Given in C: xampp htdocs Astral_mistico login.php on line 12

  • returned these errors

  • I only had a bug in $connect, I reset it to $Conn. the errors are gone so now it does not validate and does not redirect. only returns the successful connection message to the database every time

  • All right, I made the correction, try again with the code there.

  • now it does not log in any account. is only returning user and incorrect password.

  • face I wonder if I didn’t miss the BD so I uploaded a pdf of how it is done https://drive.google.com/file/d/1kqBJ-l8IzyXYDAgfCYovO5HdCvse2Rqn/view?usp=sharing

  • Dude, I made something simple here that might help you with that, check there: https://drive.google.com/file/d/1UL3nuk9ZtqVmeLNjLRVffeFPob8XtEI/view?usp=sharing

  • Our guy, after breaking his head all day I went to find out that the problem was the MD5 key. I forgot to save in the bank as MD5. I wouldn’t even log in...... I’ll even rest after this one. But thank you so much for your help...

  • klkkkk It happens...

Show 4 more comments

Browser other questions tagged

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