I'm working with my little PHP project and I'm trying to implement hashing on registration and I need to verify my hashed password when user want to log in. I tried a lot but I don't really get how I could use password_verify function in my code.
In my registration.php I have a code:
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$email = $_POST['email'];
My login.php file looks like this:
$username = $_POST['username'];
$password = $_POST['password'];
$username = htmlentities($username, ENT_QUOTES, "utf-8");
$password = htmlentities($password, ENT_QUOTES, "utf-8");
if ($result = @$connect_db->query(sprintf("SELECT * FROM users WHERE username='%s' AND password='%s'",
mysqli_real_escape_string($connect_db, $username),
mysqli_real_escape_string($connect_db, $password)))
) {
$amount = $result->num_rows;
if ($amount > 0) {
$_SESSION['logged_in'] = true;
$row = $result->fetch_assoc();
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['enter code hereemail'] = $row['email'];
$_SESSION['admin'] = $row['admin'];
unset($_SESSION['error']);
$result->free_result();
header('Location: dictionary.php');
} else {
$_SESSION['error'] = '<p class="error_m">Invalid username or password!</p>';
header('Location: index.php');
}
}
My question is about how to use password_verify function in my login.php file?
When you store the result of
password_hash()
in the database, you are storing the hashed password. To check if the inputted password is correct to log in a user, you can do something like this (pseudocode):http://php.net/manual/en/function.password-verify.php
you do not hash the password the user types into the form rather you hash the password when the user is actually registering into your site
For the login process and how to use the password_verify function
You should also look at mysqli prepared statements