35106-vm/auth/login.php
Flatlogic Bot 59d1fd0157 3.5
2025-10-22 12:02:27 +00:00

89 lines
3.3 KiB
PHP

<?php
session_start();
require_once __DIR__ . '/../db/config.php';
$errors = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = trim($_POST['email']);
$password = $_POST['password'];
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'A valid email is required.';
}
if (empty($password)) {
$errors[] = 'Password is required.';
}
if (empty($errors)) {
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT * FROM Users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user && password_verify($password, $user['password'])) {
// Password is correct, start session
$_SESSION['id'] = $user['id'];
$_SESSION['name'] = $user['name'];
$_SESSION['role'] = $user['role'];
// Redirect based on role
if ($user['role'] === 'Admin') {
header("Location: /admin/dashboard.php");
exit;
} else {
header("Location: /student/dashboard.php");
exit;
}
} else {
$errors[] = 'Invalid email or password.';
}
} catch (PDOException $e) {
$errors[] = "Database error: " . $e->getMessage();
}
}
}
require_once __DIR__ . '/../includes/header.php';
?>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h2>Login</h2>
</div>
<div class="card-body">
<?php if (!empty($errors)): ?>
<div class="alert alert-danger">
<?php foreach ($errors as $error): ?>
<p><?php echo $error; ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>
<form action="login.php" method="post">
<input type="hidden" name="role" value="<?php echo htmlspecialchars($_GET['role'] ?? 'student'); ?>">
<div class="form-group mb-3">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="form-group mb-3">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-primary w-100">Login</button>
</form>
</div>
<div class="card-footer text-center">
<p>Don't have an account? <a href="signup.php?role=<?php echo htmlspecialchars($_GET['role'] ?? 'student'); ?>">Sign up here</a>.</p>
<p><a href="forgot-password.php">Forgot Password?</a></p>
</div>
</div>
</div>
</div>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>