Refactor login logic to use database authentication instead of hardcoded credentials
This commit is contained in:
29
login.php
29
login.php
@@ -1,20 +1,37 @@
|
||||
<?php
|
||||
session_start();
|
||||
|
||||
// Hardcoded credentials for demonstration (replace with a database in production)
|
||||
$validUsername = 'dresden';
|
||||
$validPassword = 'NQSOJMqnu7e1vinfNUNRxHFotSfEcDrBde8mPT';
|
||||
try {
|
||||
// Connect to the database
|
||||
$db = new PDO('mysql:host=localhost;dbname=webform_users;charset=utf8', 'adminweb', 'NQSOJMqnu7e1vinfNUNRxHFotSfEcDrBde8mPT');
|
||||
$db->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.";
|
||||
}
|
||||
}
|
||||
?>
|
||||
|
||||
Reference in New Issue
Block a user