78 lines
2.1 KiB
PHP
78 lines
2.1 KiB
PHP
<?php
|
|
require_once 'db/config.php';
|
|
|
|
if (session_status() === PHP_SESSION_NONE) {
|
|
session_start();
|
|
}
|
|
|
|
// If user is already logged in, redirect to dashboard
|
|
if (isset($_SESSION['user_id'])) {
|
|
header('Location: index.php');
|
|
exit;
|
|
}
|
|
|
|
$errors = [];
|
|
$message = $_SESSION['message'] ?? null;
|
|
unset($_SESSION['message']);
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$email = $_POST['email'] ?? '';
|
|
$password = $_POST['password'] ?? '';
|
|
|
|
if (empty($email)) {
|
|
$errors[] = 'Email is required';
|
|
}
|
|
if (empty($password)) {
|
|
$errors[] = 'Password is required';
|
|
}
|
|
|
|
if (empty($errors)) {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
|
|
$stmt->execute([$email]);
|
|
$user = $stmt->fetch();
|
|
|
|
if ($user && password_verify($password, $user['password'])) {
|
|
$_SESSION['user_id'] = $user['id'];
|
|
$_SESSION['username'] = $user['username'];
|
|
$_SESSION['role'] = $user['role'];
|
|
header('Location: index.php');
|
|
exit;
|
|
} else {
|
|
$errors[] = 'Invalid email or password';
|
|
}
|
|
}
|
|
}
|
|
?>
|
|
<?php include 'auth_header.php'; ?>
|
|
|
|
<div class="form-container">
|
|
<h2>Login</h2>
|
|
<?php if ($message): ?>
|
|
<div class="success">
|
|
<p><?php echo htmlspecialchars($message); ?></p>
|
|
</div>
|
|
<?php endif; ?>
|
|
<?php if (!empty($errors)): ?>
|
|
<div class="errors">
|
|
<?php foreach ($errors as $error): ?>
|
|
<p><?php echo htmlspecialchars($error); ?></p>
|
|
<?php endforeach; ?>
|
|
</div>
|
|
<?php endif; ?>
|
|
<form action="login.php" method="post">
|
|
<div class="form-group">
|
|
<label for="email">Email</label>
|
|
<input type="email" name="email" id="email" required>
|
|
</div>
|
|
<div class="form-group">
|
|
<label for="password">Password</label>
|
|
<input type="password" name="password" id="password" required>
|
|
</div>
|
|
<button type="submit">Login</button>
|
|
</form>
|
|
<p>Don't have an account? <a href="register.php">Register here</a>.</p>
|
|
</div>
|
|
|
|
<?php include 'auth_footer.php'; ?>
|