35603-vm/login.php
Flatlogic Bot 23eab8271d v2
2025-11-09 18:56:18 +00:00

88 lines
3.0 KiB
PHP

<?php
require_once __DIR__ . '/db/config.php';
$errors = [];
$username = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';
// Validation
if (empty($username)) {
$errors[] = 'Username is required.';
}
if (empty($password)) {
$errors[] = 'Password is required.';
}
// If no validation errors, check credentials
if (empty($errors)) {
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT id, username, password FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user && password_verify($password, $user['password'])) {
// Regenerate session ID to prevent session fixation
session_regenerate_id(true);
// Store user info in session
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
// Redirect to the main page
header("Location: index.php");
exit;
} else {
$errors[] = 'Invalid username or password.';
}
} catch (PDOException $e) {
$errors[] = "Database error: " . $e->getMessage();
}
}
}
require_once __DIR__ . '/includes/header.php';
?>
<div class="row justify-content-center">
<div class="col-lg-5">
<div class="card task-card">
<div class="card-body p-4">
<h1 class="card-title h3 mb-4 text-center">Login to Your Account</h1>
<?php if (!empty($errors)): ?>
<div class="alert alert-danger">
<?php foreach ($errors as $error): ?>
<p class="mb-0"><?php echo htmlspecialchars($error); ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>
<form action="login.php" method="POST">
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" id="username" name="username" value="<?php echo htmlspecialchars($username); ?>" 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 w-100 py-2">Login</button>
</form>
<div class="text-center mt-4">
<p class="mb-0">Don't have an account? <a href="register.php">Register here</a>.</p>
</div>
</div>
</div>
</div>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>