bubble_chart StackLab

Role Based Access Login PHP

5 steps · pending Not started · person_outline Guest
arrow_back Back

Create the Authentication Functions

Access the config/functions.php

code text
it34a/
├── index.php
├── config/
|   ├── ***functions.php***
├── auth/
├── app/
│   ├── admin/
│   ├── manager/
│   └── user/
└── includes/
Login Function The login function accepts either an email address or username, retrieves the matching account, verifies the password, and creates the authenticated session.
code html
function loginUser($pdo, $login, $password)
{
    $sql = "
        SELECT
            user_id,
            user_email,
            user_username,
            user_password,
            user_role
        FROM users
        WHERE user_email = :login
           OR user_username = :login
        LIMIT 1
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([':login' => $login]);

    $user = $stmt->fetch();

    if (!$user) {
        return false;
    }

    if (!password_verify($password, $user['user_password'])) {
        return false;
    }

    $_SESSION['user_id'] = $user['user_id'];
    $_SESSION['user_email'] = $user['user_email'];
    $_SESSION['user_username'] = $user['user_username'];
    $_SESSION['user_role'] = $user['user_role'];

    return true;
}
Add the requireLogin() function to track the session_id
code text
function requireLogin()
{
    if (!isset($_SESSION['user_id'])) {
        header('Location: ' . BASE_URL . '/index.php');
        exit;
    }
}
Lastly add the requireRole() to get the user_role from the session variables
code text
function requireRole($role)
{
    requireLogin();

    if ($_SESSION['user_role'] !== $role) {
        http_response_code(403);
        die('Access denied.');
    }
}
Save your file

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