I'm working on a login page and the password_verify() always returns false when getting the hash from the DB but prints true when using static values
Here's my code :
<?php
require_once "ID.php";
$message = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Connect to the database
$conn = new mysqli($DB_SERVER, $DB_USER, $DB_PASSWORD, $DB_NAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$pseudo = $_POST['pseudo'];
$passwordInput = trim($_POST['password']);
// Fetch the stored password hash
$stmt = $conn->prepare("SELECT password FROM users WHERE Pseudo = ?");
$stmt->bind_param("s", $pseudo);
$stmt->execute();
$stmt->bind_result($storedHash);
$stmt->fetch();
// Debugging: Output the fetched stored hash and length
echo "Stored Hash: $storedHash<br>";
echo "Stored Hash Length: " . strlen($storedHash) . "<br>";
// Check if we found the user
if ($storedHash) {
// Debugging: Check if password verification passes
$verifyResult = password_verify($passwordInput, $storedHash) ? "true" : "false";
echo "Password verify result: $verifyResult<br>";
if (password_verify($passwordInput, $storedHash)) {
$message = "Login successful!";
} else {
$message = "Invalid username or password.";
}
} else {
$message = "User not found.";
}
$stmt->close();
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<?php if ($message) echo "<p>$message</p>"; ?>
<form method="POST" action="">
<input type="text" name="pseudo" placeholder="Username" required><br>
<input type="password" name="password" placeholder="Password" required><br>
<button type="submit">Login</button>
</form>
</body>
</html>
I tried using static values and it worked but the second its not static it doesn't work anymore
password_verify()playground$storedHash. That's a reasonable name: It's a hash, and it came from the database. I would have preferred$passwordHash, which is a more accurate description of the value. But in your database you call itpassword. It's not a password, and that name looks nothing like$storedHash. What is it? A password or a hash? See, if you call them bothpasswordHash, in your database and your PHP code, you can instantly see what's what. Choosing names is hard, I know.die()and print raw query errors. Please nevertrim()passwords. Why do you callpassword_verify()twice when once is enough? What are the column details. This question Needs Debugging Details.