57 lines
1.7 KiB
PHP
57 lines
1.7 KiB
PHP
<?php
|
|
session_start();
|
|
|
|
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']));
|
|
|
|
// 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;
|
|
$_SESSION['user'] = $user['username'];
|
|
|
|
// Redirect to the main page
|
|
header("Location: index.php");
|
|
exit;
|
|
} else {
|
|
$error = "Invalid username or password.";
|
|
}
|
|
}
|
|
?>
|
|
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<title>Login</title>
|
|
</head>
|
|
<body>
|
|
<h2>Login</h2>
|
|
<?php if (isset($error)) echo "<p style='color: red;'>$error</p>"; ?>
|
|
<form method="post">
|
|
<label for="username">Username:</label>
|
|
<input type="text" id="username" name="username" required>
|
|
<br>
|
|
<label for="password">Password:</label>
|
|
<input type="password" id="password" name="password" required>
|
|
<br>
|
|
<button type="submit">Login</button>
|
|
</form>
|
|
</body>
|
|
</html>
|