<?
php
// includes/auth.php
session_start();
require_once 'db.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
// Prevent SQL injection
$stmt = $conn->prepare("SELECT id, username, password, role FROM users WHERE
username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
// Check if user exists
if ($stmt->num_rows == 1) {
$stmt->bind_result($id, $user, $hashed_password, $role);
$stmt->fetch();
if (password_verify($password, $hashed_password)) {
// Login success
$_SESSION['user_id'] = $id;
$_SESSION['username'] = $user;
$_SESSION['role'] = $role;
header("Location: ../dashboard.php");
exit();
} else {
header("Location: ../login.php?error=Incorrect password");
exit();
}
} else {
header("Location: ../login.php?error=User not found");
exit();
}
} else {
header("Location: ../login.php");
exit();
}