How to allow login into the system validating user and password by php database?

Asked

Viewed 962 times

0

Next guys: I have an html form where I take this data and send it to a php action where the data is processed and sent to the database. This part is ok, the data goes right and everything. Now I have another html login screen. This screen the action is forwarded to a php validation.php where the code is:

<?php

session_start();

//INICIA A CONEXÃO COM O BANCO DE DADOS
$servername = "localhost";
$username = "meuUsuario";
$password = "minhaSenha";
$dbname = "meuBanco";

$conexao = new mysqli($servername, $username, $password, $dbname);

if (!$conexao) {
    die("Não foi possível conectar ao banco de dados" . mysqli_connect_error());
}

$usuario = mysqli_real_escape_string($conexao, $_POST['usuario']);
$senha = mysqli_real_escape_string($conexao, md5($_POST['senha']));

// Validação do usuário/senha digitados
$sql = "SELECT id, Nome, Senha FROM cadastroMorador WHERE Usuario = '$usuario' AND Senha = '$senha' LIMIT 1";
$query = mysqli_query($conexao, $sql);
if ($query) {
    // Mensagem de erro quando os dados são inválidos e/ou o usuário não foi encontrado
    $row_usuario = mysqli_fetch_assoc($query);
    if(password_verify($senha, row_usuario['Senha'])){
       header("Location: index.html");

    } else {
    echo "Login inválido!";
    header("Location: signin.html"); 
    }


} else {
    echo "Login inválido!";
    //header("Location: signin.html"); 


// Se a sessão não existir, inicia uma
if (!isset($_SESSION)) session_start();
// Salva os dados encontrados na sessão
$_SESSION['UsuarioID'] = $resultado['id'];
$_SESSION['UsuarioNome'] = $resultado['nome'];
//$_SESSION['UsuarioNivel'] = $resultado['nivel'];
// Redireciona o visitante

}   

?>

From what I noticed when trying to access it is not comparing the password with the password that is with database (I used that md5, I know it is not recommended but I do not know yet change to do the correct way). I believe the problem is there. Can someone please help me? I can’t login because the password is not compared to the password in the database.

  • It makes no sense to include the password in the query and use password_verify at the same time. If you save a password hash in the database, do not include the password entered in the query query, only the user. Then this code should work, as long as the password has been generated with password_hash().

  • @bfavaretto this is, the password was not generated with password_hash(); I will try to fix this and make the change here to see if it works.

  • It is safer to generate with password_hash even, MD5 that you mentioned should never be used for passwords. But if you need to access something already saved, generate the MD5 hash of the password that is entered in the login and in the query compare this hash with the value of the database. If the query returns a record for the user + hash pair, the login may be valid.

  • @bfavaretto managed to generate the password by password_hash(). I looked in the database and it is generated correctly. Now how should I change in my code above to be correct?

  • Take this part of the query: AND Senha = '$senha'

  • I took it, and it keeps going wrong. It enters Else and gives "Invalid Login". When I send the password to the bank I send it like this: $password = password_hash($_POST["password"], PASSWORD_DEFAULT); $confirms = password_hash($_POST["Confirm password"], PASSWORD_DEFAULT); This way it is going to the bank with hash. @bfavaretto

  • Take the md5 up there too. I hadn’t seen him there.

  • Yeah, keep making the same mistake. I can’t find what.

  • Put it on this line like this: $query = mysqli_query($connected, $sql) or die(mysqli_error($connected)); it will indicate the error.

Show 4 more comments
No answers

Browser other questions tagged

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