Search code examples
phppassword-hash

How to use password_hash Register And Login


I'm trying to figure out how to use password_hash on register and login systems.

Currently I'm using password_hash like this to register my users.

$pass = $_POST['Pass']; 
$hashed_password = password_hash($pass, PASSWORD_DEFAULT); 

$stmt = $conn->prepare("INSERT INTO `usuario`(`Nick`, `Nombre_u`, `Apellidos`, `e-mail`, `Password`, `Domicilio`, `Colonia`, `Codigo_Postal`, `Cuidad`, `Estado`, `Telefono`) VALUES (?, ?, ?, ?, ?, ? , ?, ?, ?, ?, ?)"); 
$stmt->bind_param( "sssssssisss", $nick, $nombre, $apellidos, $mail, $hashed_password, $domicilio, $colonia, $cp, $cuidad, $estado,  $telefono); 
$stmt->execute(); 
header("Location: ../Registrado.php?Done=Welcome"); 

And I'm loging my users this way.

$usuario = $_POST["Nick"];
$contra = $_POST["Pass"]; 
$hashed_password = password_hash($contra, PASSWORD_DEFAULT);  
$stmt = $conn->prepare("SELECT Nick, Password FROM usuario WHERE Nick = ? AND Password= ?");
$stmt->bind_param( "ss", $usuario, $hashed_password); 
$stmt->execute();
$stmt->store_result(); 
$stmt->bind_result($a, $b); 
if($stmt->fetch() == 0){ 
    header("Location: ../Entrar.php?message=Error");
    exit();
} 
else {  
    session_start(); 
    $_SESSION['Usuario'] = $a; 
    $_SESSION['estado'] = 'Autenticado';  
    header("Location: ../../Index.php"); 
    exit();
}    

The way I'm Understanding It's that my query will do something like this.

First will take my input Eg:"123", then hashed_password will turn my input into Eg:"$2y$10$BvFW3ott5f7JvZ4rCa", And my query will do his work like this.

SELECT Nick, Password FROM usuario WHERE Nick = 'User' AND Password= '$2y$10$BvFW3ott5f7JvZ4rCa'

But I'm Still returning to my Login Form instead log in my user.

What am I doing wrong?


Solution

  • Ok I made this work with password_verify()

    $usuario = $_POST["Nick"];
    $contra = $_POST["Pass"];   
    $stmt = $conn->prepare("SELECT Nick, Password FROM usuario WHERE Nick = ?");
    $stmt->bind_param( "s", $usuario); 
    $stmt->execute();
    $stmt->store_result(); 
    $stmt->bind_result($a, $b);   
    
    if($stmt->fetch() == 0){ 
        header("Location: ../Entrar.php?message=Error");
        exit();
    }
    else {  
        if(password_verify($contra, $b)) {
            session_start(); 
            $_SESSION['Usuario'] = $a; 
            $_SESSION['estado'] = 'Autenticado';  
            header("Location: ../../Index.php"); 
            exit; 
        }
        else{ 
            header("Location: ../Entrar.php?message=Error");
            exit;
        }
    } 
    

    Thank you for all those comments. And yes martinstoeckli that was the answer to my question thank you