bubble_chart StackLab

Role Based Access Login PHP

5 steps · pending Not started · person_outline Guest
arrow_back Back

Create the Login Page

index.php The login page accepts either a username or email address and a password.

code text
<?php
require_once __DIR__ . '/config/config.php';

if (isset($_SESSION['user_id'])) {
    header('Location: ' . BASE_URL . '/app/' . $_SESSION['user_role'] . '/index.php');
    exit;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $login = trim($_POST['login'] ?? '');
    $password = $_POST['password'] ?? '';

    if (loginUser($pdo, $login, $password)) {
        header('Location: ' . BASE_URL . '/app/' . $_SESSION['user_role'] . '/index.php');
        exit;
    }

    $error = 'Invalid username/email or password.';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
</head>
<body>

<h1>PHP PDO Authentication</h1>

<?php if ($error): ?>
    <p><?= htmlspecialchars($error) ?></p>
<?php endif; ?>

<form method="POST">
    <label>Username or Email</label><br>
    <input type="text" name="login" required><br><br>

    <label>Password</label><br>
    <input type="password" name="password" required><br><br>

    <button type="submit">Sign In</button>
</form>

</body>
</html>

login Sign in to save your progress permanently. info Progress is saved in your browser session
format_list_numbered Step 5 of 5