How can role-based access control be implemented in PHP to restrict access to specific pages based on user roles?

Role-based access control in PHP can be implemented by creating a system where each user is assigned a role (such as admin, moderator, or user) and then checking the user's role before allowing access to specific pages. This can be achieved by storing user roles in a database and checking the user's role against the required role for each page.

// Check user role before allowing access to a specific page
session_start();

// Define user roles
$roles = [
    'admin' => 1,
    'moderator' => 2,
    'user' => 3
];

// Check if user is logged in and has a role
if(isset($_SESSION['role']) && isset($roles[$_SESSION['role']])) {
    $requiredRole = 2; // Set required role for this page (e.g., moderator)
    
    // Check if user has the required role to access the page
    if($roles[$_SESSION['role']] >= $requiredRole) {
        // User has the required role, allow access to the page
        echo "You have access to this page.";
    } else {
        // User does not have the required role, redirect to a different page
        header("Location: unauthorized.php");
        exit();
    }
} else {
    // User is not logged in, redirect to the login page
    header("Location: login.php");
    exit();
}