Background - I have spent the last hour or so looking through various posts sites and so on to see why my password checking function has suddenly stopped working.
Every time I try to use it, it returns false, including when the inputted password is correct.
I have echoed my input and my hash, both of which match fine (by comparing the hash in the table to the one echoed).
However, when these variables are put through password_verify
, it returns false 100% of the time.
What do I think is wrong? - Based on a post from an external site, I think this is due to the way that my hashedPassword
variable is being parsed. When is compares the two, something goes wrong in the variable type and returns false.
What does my code and database look like? -
users
table. Contains other columns.
userId | username | password
----------------------------
1 | example | temp1
Class containing the password checker function. (Have trimmed away try/catch)
public function checkPasswordCorrect($username, $password) { // Returns true is the entered password is correct and false if it isn't.
// This creates a mysqli context to run the connection through.
$mysqli = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbPlusPlus);
// If there is an error connecting to the database, it will be printed and the process will close.
if (mysqli_connect_errno()) {
printf("Connect failed: %s
", mysqli_connect_error());
exit();
}
$sql = "SELECT password FROM users WHERE username='$username'";
$result = $mysqli->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
$hashedPassword = $row["password"];
$mysqli->close();
echo $password."<br>".$hashedPassword."<br>"; // The input is correct and the hash matches that in the table.
// We return a value of true or false, depending on the outcome of the verification.
if(password_verify($password, $hashedPassword)) {
echo "return true";
return true;
}
else {
echo "return false";
return false;
}
}
By echoing $hashedPassword
just before using password_verify
, the hash matches by manually checking it, as you can see by the output below.
temp0022
$2y$10$9TgjJzSaqOB
return false
What am I asking? -
Is there a better way of checking password inputs, more specifically, the way I'm pulling the information from the table (there must be some simpler way of doing this).
Is the variable parsing to blame? Is there any documentation or articles available for this topic that I haven't seen?
What am I aware of? - My usage of mysqli
is shocking, I'm new to it. I am also aware that there are similar answers out there, but seem to be down to some kind of syntax error more than anything else.
Thank you for taking the time to help! :D
For all of those of you who are worried that I'm going to be hit by SQL injection attacks: I have since modified this example code massively and am using prepared, statements. Thank you for your concern :)