35418-vm/login.php
2025-11-02 14:43:46 +00:00

44 lines
1.1 KiB
PHP

<?php
session_start();
require_once 'db/config.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Location: index.php');
exit();
}
$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '');
if (empty($username) || empty($password)) {
header('Location: index.php?login_error=1#login');
exit();
}
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password_hash'])) {
// Password is correct, start session
session_regenerate_id();
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
$_SESSION['user_role'] = $user['user_role'];
header('Location: dashboard.php');
exit();
} else {
// Invalid credentials
header('Location: index.php?login_error=1#login');
exit();
}
} catch (PDOException $e) {
// In a real app, log the error
header('Location: index.php?login_error=1#login');
exit();
}
?>