34766-vm/login.php
2025-10-08 05:39:35 +00:00

94 lines
3.1 KiB
PHP

<?php
require_once 'db/config.php';
// Extend session lifetime to 30 days
ini_set('session.gc_maxlifetime', 30 * 24 * 60 * 60);
session_set_cookie_params(30 * 24 * 60 * 60);
session_start();
$errors = [];
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)) {
try {
$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['user_email'] = $user['email'];
$_SESSION['user_role'] = $user['role'];
if ($user['first_login']) {
$updateStmt = $pdo->prepare("UPDATE users SET first_login = 0 WHERE id = ?");
$updateStmt->execute([$user['id']]);
// Here you could redirect to a welcome page, e.g., header("Location: welcome.php");
}
// Role-based redirection
switch ($user['role']) {
case 'ngo':
header("Location: dashboard.php");
exit;
case 'restaurant':
header("Location: listings.php");
exit;
default:
// Default redirect for any other roles
header("Location: dashboard.php");
exit;
}
} else {
$errors[] = 'Invalid email or password';
}
} catch (PDOException $e) {
$errors[] = "Database error: " . $e->getMessage();
}
}
}
?>
<?php include 'partials/header.php'; ?>
<div class="container py-5">
<div class="row">
<div class="col-md-6 mx-auto">
<h2 class="text-center mb-4">Login</h2>
<?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">
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</div>
</div>
<?php include 'partials/footer.php'; ?>