How can PHP developers properly verify md5 encrypted passwords from a MySQL database in a login script?
When verifying md5 encrypted passwords from a MySQL database in a login script, PHP developers should retrieve the stored password hash from the database based on the provided username, then hash the input password using md5 and compare it with the stored hash. If the hashes match, the login is successful; otherwise, it fails.
// Retrieve the stored password hash from the database based on the provided username
$query = "SELECT password FROM users WHERE username = :username";
$stmt = $pdo->prepare($query);
$stmt->execute(['username' => $username]);
$user = $stmt->fetch();
if ($user) {
// Hash the input password using md5
$input_password_hash = md5($password);
// Compare the hashed input password with the stored hash
if ($input_password_hash === $user['password']) {
// Passwords match, login successful
echo "Login successful!";
} else {
// Passwords do not match, login failed
echo "Incorrect username or password";
}
} else {
// Username not found in the database
echo "Incorrect username or password";
}
Related questions
-
SQL injection PDO prepared statements
-
optional parameters PHP functions pitfalls
-
cURL API timeout