ive created this login system for registration and logging in, how ever when i try to log in with a registered user it says the password or username is incorrect.
registration.php
// Create a new mysqli connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check if the connection was successful
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Validate and sanitize user inputs
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$confirm_password = mysqli_real_escape_string($conn, $_POST['confirm_password']);
if ($password !== $confirm_password) {
echo "Passwords do not match.";
} else {
// Hash the password
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
// Use a prepared statement to insert data
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $hashedPassword);
if ($stmt->execute()) {
echo "Registration successful. You can now <a href='login.html'>log in</a>.";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
}
// Close the database connection
$conn->close();
}
Here is login.php
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = $_POST['password']; // No need to escape here
// Use prepared statement to avoid SQL injection
$stmt = $conn->prepare("SELECT username, password FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
$stmt->bind_result($db_username, $db_password);
$stmt->fetch();
if (password_verify($password, $db_password)) {
$_SESSION['username'] = $db_username;
header("Location: dashboard.php");
} else {
echo "Invalid username or password.";
}
} else {
echo "Invalid username or password.";
}
$stmt->close();
$conn->close();
} ?>
I have reviewed my code and i cannot figure out why i cannot login. I think I am comparing password hash correctly but i am new to php and i am doing this as a learning excercise. I dont think there is an error in the database itself because everything is saving correctly in the tables and seems to be working fine. any help would be appreciated on fixing or explaining to me how logging in works and how to create a user signup/login system using php