From c568ac09bb06088c12e1ee06767fea9f57faaa4e Mon Sep 17 00:00:00 2001 From: alexpolo1 Date: Thu, 1 May 2025 21:20:33 +0200 Subject: [PATCH] Refactor login logic to use database authentication instead of hardcoded credentials --- login.php | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/login.php b/login.php index 894e1b6..d96be55 100644 --- a/login.php +++ b/login.php @@ -1,20 +1,37 @@ setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); +} catch (PDOException $e) { + die("Database connection failed: " . $e->getMessage()); +} if ($_SERVER['REQUEST_METHOD'] === 'POST') { + // Sanitize user inputs $username = htmlspecialchars(trim($_POST['username'])); $password = htmlspecialchars(trim($_POST['password'])); - if ($username === $validUsername && $password === $validPassword) { + // Fetch user from the database + $stmt = $db->prepare("SELECT * FROM users WHERE username = ?"); + $stmt->execute([$username]); + $user = $stmt->fetch(PDO::FETCH_ASSOC); + + if ($user && password_verify($password, $user['password'])) { + // Regenerate session ID to prevent session fixation + session_regenerate_id(true); + + // Set session variables $_SESSION['loggedin'] = true; - header('Location: index.php'); + $_SESSION['user'] = $user['username']; + + // Redirect to the main page + header("Location: index.php"); exit; } else { - $error = 'Invalid username or password.'; + $error = "Invalid username or password."; } } ?>