user9161375
user9161375

Reputation:

Cannot get password_verify to work (PHP, MYSQL)

I've set up password_hash in my registration script. Can't figure out how to use password_verify correctly to log into my website.

Screenshot of DB: https://i.sstatic.net/j8xqm.png

Login Code (says "incorrect login, even when the password is correct):

<?php  
    require 'db_connect.php';

    if (isset($_POST['username']) and isset($_POST['password'])){

        $username = $_POST['username'];
        $password = $_POST['password'];

        $query = "SELECT * FROM `member` WHERE username='$username'";

        $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
        $count = mysqli_num_rows($result);

        if (password_verify($_POST['password'],$hashword))
        {
             echo "Correct login";
        }
            else
        {
            echo "incorrect login";
        }
    }
?>

Registration Code(Works great, no issues with DB connection either):

<?php
    require 'db_connect.php';

    $email = $_POST['email'];
    $username = $_POST['username'];
    $password1 = $_POST['password1'];
    $password2 = $_POST['password2'];

    if($password1 != $password2)
        header('Location: registration.html');
    if(strlen($username) > 25)
        header('Location: registration.html');

    $hashword = password_hash($password,PASSWORD_DEFAULT);

    $query = "INSERT INTO member ( username, password, email)
    VALUES ( '$username', '$hashword', '$email');";

    $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
    mysql_close();

    header('Location: login.html');
?>

Upvotes: 0

Views: 438

Answers (1)

RamC
RamC

Reputation: 1287

From your code, it looks like you are not checking the $_POST['password'] with the correct hashword which was inserted into the database.

The variable $hashword will have nothing and hence password_verify fails.

Fetch the value of password which was stored in the database and store it in $hashword variable then use it in the password_verify function for it to work as intended.

Example

$row = mysqli_fetch_assoc($result);
$hashword =  $row['password'];

Usage

$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);

$row = mysqli_fetch_assoc($result);
$hashword =  $row['password'];

if (password_verify($_POST['password'],$hashword))
{
     echo "Correct login";
}
    else
{
    echo "incorrect login";
}

Upvotes: 1

Related Questions