Problem with login system - array

2

Hello. I'm creating a login system for study purposes.

I have identified in the file that is not populating the array with the information of the database ... and yes, I already made sure that the entered email and password already exists in the database.

Following login.php file:

<?php

require_once 'init.php';

// resgata dados digitados no formulario
$email = isset($_POST['email']) ? $_POST['email']: '';
$senha = isset($_POST['senha']) ? $_POST['senha']: '';
// Cria o hash da senha
$seg_senha = password_hash($senha, PASSWORD_DEFAULT);

// Verifica se os campos do form nao estao vazios
if(empty($email) || empty($senha)){
    echo 'Informe Email e Senha';
    exit;
}

// Comando no banco de dados
$pdo = db_connect();    // Abre conexão com o banco

$sql = "SELECT id, nome FROM usuarios WHERE email = :email AND senha = :senha";
// Cria query

$stmt = $pdo->prepare($sql);    // Prepare da query

$stmt->bindParam(':email', $email);
// Atribui valor do campo email no valor email da query
$stmt->bindParam(':senha', $seg_senha);
// Atribui valor do campo senha no valor senha da query

$stmt->execute();   // Execute na query

$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);   // Cria array associativo

if(count($arr) <= 0){   // Verifica se existe elemento no array
    echo "<script language='javascript' type='text/javascript'>alert('Login e/ou senha incorretos');window.location.href='../login.php';</script>";
    exit;
}

// Pega o primeiro usuario
$user = $arr[0];

// Inicia a sessão
session_start();
$_SESSION['logged_in'] = true;
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['nome'];

header('Location: ../index1.php');

If I comment from the line if(count($arr) <= 0){ down, and I put a var_dump($arr); below $arr = $stmt->fetchAll(PDO::FETCH_ASSOC); it returns an empty array

C:\wamp64\www\ProjetoALPHA\core\login.php:33:
array (size=0)
  empty

Could anyone help me?

Thank you!

    
asked by anonymous 03.01.2017 / 23:23

1 answer

5

This will not practically generate the same hash that was written to the DB:

$seg_senha = password_hash($senha, PASSWORD_DEFAULT);

and, among other things, that's why the function is safer than simple hashes . In addition to using better hashes , the function generates a random salt every time it is used.

Primitive and insecure password systems were made with this technique being tested in the question, and these are vulnerable to attacks of pre-calculated password tables.

To understand better, see this post:

  

How to safely have password hash?

To understand that it does not work, take this test:

echo password_hash( '123456', PASSWORD_DEFAULT)."<br>\n";
echo password_hash( '123456', PASSWORD_DEFAULT)."<br>\n";
echo password_hash( '123456', PASSWORD_DEFAULT)."<br>\n";
echo password_hash( '123456', PASSWORD_DEFAULT)."<br>\n";
echo password_hash( '123456', PASSWORD_DEFAULT)."<br>\n";

Check out IDEONE .

You noticed that the password is the same, but the hash changes? This is why generating the hash again when doing SELECT does not work.


Solution for your case:

The correct thing is that you can recover the DB data with that user, and hash , and only then test in PHP like this:

// ELIMINE ISSO DO LOGIN:
// $seg_senha = password_hash($senha, PASSWORD_DEFAULT);
// O password_hash só deve ser usado ao salvar uma senha, não ao ler.

$pdo = db_connect();
$sql = "SELECT id, nome, senha FROM usuarios WHERE email = :email";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':email', $email); // No caso o bindValue é mais adequado
$stmt->execute();

$arr = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($arr) < 1) {
    ... USUARIO NAO EXISTE ...
} else if( password_verify( $senha, $arr[0]['senha'] ) ) {
    ... BEM VINDO AO SISTEMA ...
} else {
    ... SENHA ERRADA ...
} 

Or if you do not want to give the tip if it was the wrong user or password, to make it difficult to attack, change the ending to

if( ( count($arr) < 1) || (!password_verify( $senha, $arr[0]['senha'])) ) {
    ... SENHA OU USUÁRIO ERRADO ...
} else {
    ... BEM VINDO ...
} 

In general, this is it. Fit for your specific case.

Manual:

  

link

    
03.01.2017 / 23:41