Ozay34
Ozay34

Reputation: 107

comparing a password to a hash queried from database?

I send a password to php to get compared to the hash stored in the database.

my php is:

$enteredUser = $_POST["username"];
$enteredPass = $_POST["password"];
$query = mysqli_query($con, "SELECT passhash FROM user WHERE `username` = '$enteredUser'");
$passHash = mysql_result($query, 0);
if(password_verify($enteredPass, $passHash)){
    echo "success";
}else{
    echo "failure";
}

I also tried using mysqli_fetch_array() as well, but it still doesn't work. Does anyone know why this isn't working? thanks in advance to anyone who can help. (on a side note, $passHash returns null)

Upvotes: 0

Views: 76

Answers (3)

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

Give this a try:

$enteredUser = mysqli_real_escape_string($con,$_POST["username"]);
$enteredPass = mysqli_real_escape_string($con,$_POST["password"]);

$sql = "SELECT * FROM `user` WHERE `username` = '$enteredUser'";
$result = $con->query($sql);
if ($result->num_rows === 1) {
    $row = $result->fetch_array(MYSQLI_ASSOC);
    if (password_verify($enteredPass, $row['passhash'])) 
    {
    echo "Success";
    }
    else {
    echo "Sorry";
    }

Upvotes: 0

JBES
JBES

Reputation: 1557

You are mixing two extensions, mysqli and mysql - mysqli_query and then mysql_result.

You are also open to SQL injection and should be sanitising your POST input before passing it directly to MySQL.

mysqli_query returns a result object and you then need to fetch the results from that object.

mysqli_fetch_row will return one row.

$enteredUser = $_POST["username"];
$enteredPass = $_POST["password"];
//...
$resultset = mysqli_query($con, "SELECT passhash FROM user WHERE `username` = '$enteredUser'");
$result = mysqli_fetch_row($resultset);
if(password_verify($enteredPass,$result[0])){
    echo "success";
}else{
    echo "failure";
}

Upvotes: 1

Ozay34
Ozay34

Reputation: 107

I did solve my own problem with a simple while loop, i guess it will work fine, thanks everyone for your input:

$passHash = ''; 
while ($row = mysqli_fetch_array($query)) { 
    $passHash .= $row["passhash"]; 
} 

Upvotes: 0

Related Questions