How can PHP be used for user login authentication?
User login authentication can be implemented in PHP by checking the entered username and password against a database of users. This involves querying the database to retrieve the user's information and comparing the password hash stored in the database with the hash of the entered password. If the credentials match, the user is considered authenticated and can access the protected areas of the website.
// Assuming connection to the database has been established
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password'])) {
// User is authenticated, set session variables or redirect to a protected page
$_SESSION['user_id'] = $user['id'];
header("Location: dashboard.php");
} else {
// Authentication failed, redirect back to login page with an error message
header("Location: login.php?error=1");
}