I am learning how to use prepared statements and I thought I would try out a login system (simple) using the password_hash() and password_verify() functions. I have succesffuly inserted data in using prepared statemernts, now I wish to verify the password and do something with the user.
I seem to be getting back my fail message at this stage:
$stmt = $conn->prepare("SELECT username, password FROM users WHERE username = ?");
$stmt->bind_param('s', $username);
$username = $_POST['ulogin'];
$password = $_POST['upassword'];
$stmt->execute();
$stmt->bind_result($username, $password);
$row = $stmt->fetch();
if ($stmt->num_rows == 1) {
if (password_verify($password, $row['user_password'])) {
echo 'success';
}
} else {
echo "Wrong data";
}
$stmt->close();
$conn->close();
If I do a var_dump($stmt->fetch()); and the login username is correct is comes back as bool(true)
Im not sure how to attempt to verify the password now.
<?php
$stmt = $conn->prepare("SELECT username, password FROM users WHERE username = ?");
$stmt->bind_param('s', $username);
$username = $_POST['ulogin'];
$password = $_POST['upassword'];
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc(); //fetch DB results
if ($row && password_verify($password, $row['password'])) {
echo 'success'; // password_verify success!
} else {
echo 'failed';
}
You do not necessarily need to check for number of rows. Also have an else statement if the password is not verified for any reason
This is one of your problems:
$password = $_POST['upassword'];
...
$stmt->bind_result($username, $password);
...
if (password_verify($password, $row['user_password'])) {
You are overwriting your $password variable so it is no longer the posted value.
Using the POST value should solve the problem:
if (password_verify($_POST['upassword'], $row['user_password'])) {
or
if (password_verify($_POST['upassword'], $password)) {
as you have bound the password from the result to that variable.
Also, if your username in the database is unique, you can replace:
$row = $stmt->fetch();
if ($stmt->num_rows == 1) {
with:
if ($row = $stmt->fetch()) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With