How can the use of RBAC (Role-Based Access Control) improve the management of user access rights in a PHP application?

Issue: Managing user access rights in a PHP application can become complex and error-prone as the number of users and roles increases. RBAC (Role-Based Access Control) can help simplify this process by assigning users to roles and granting permissions based on those roles.

// Implementing RBAC in a PHP application

// Define roles and their corresponding permissions
$roles = [
    'admin' => ['create', 'read', 'update', 'delete'],
    'editor' => ['create', 'read', 'update'],
    'viewer' => ['read']
];

// Check if user has permission based on their role
function hasPermission($userRole, $permission) {
    global $roles;
    return in_array($permission, $roles[$userRole]);
}

// Example usage
$userRole = 'admin';
if(hasPermission($userRole, 'delete')) {
    echo "User has permission to delete.";
} else {
    echo "User does not have permission to delete.";
}