I know this should be simple but I'm having some trouble trying to verify the password hash during login.
Had this in my registration handler:
else {
$hash = password_hash($pass, PASSWORD_BCRYPT);
$query = "INSERT INTO users (user_name, user_email, user_pass, user_country, user_month, user_day, user_year, profile_pic, register_date, num_posts, num_likes, user_closed, friend_array) VALUES ('$name', '$email', '$hash', '$country', '$month', '$day', '$year', '$profile_pic', '$date', '0', '0', 'no', ',')";
$result = mysqli_query ($con, $query);
if($query) {
$_SESSION ['user_name']=$name;
header("Location:home.php");
exit();
}
Login handler:
if(isset($_POST['login'])){
$name = mysqli_real_escape_string ($con, $_POST['name']);
$pass = mysqli_real_escape_string ($con, $_POST['pass']);
$get_user = "SELECT * FROM users WHERE user_name='$name' AND user_pass='$pass'";
$run_user = mysqli_query ($con, $get_user);
$check = mysqli_num_rows ($run_user);
if ($check==1) {
$row = mysqli_fetch_assoc($run_user);
$hash = $row['user_pass'];
if(password_verify($pass, $hash)){
$_SESSION ['user_name']=$name;
if(isset($_POST['remember_me'])){
setcookie("user_name", $name, time()+31556926);
}
header("Location:home.php");
exit();
}
else {
echo "Incorrect username or password.";
}
You're trying to match the record based on the entered password, which won't be the same as the stored hashed password:
... AND user_pass='$pass'
Just get the user record based on the username:
SELECT * FROM users WHERE user_name='$name'
(Important: I'm just copying/pasting your code for brevity and simplicity. But you should really start using query parameters instead of trying to directly sanitize user input.)
Once you've fetched the record, then you validate the password with password_verify()
as you currently do. (Though it looks like if the password is incorrect you don't return any message to the user indicating this. You may want another else
block in there for when password_verify()
returns false
.)