What are the best practices for handling user permissions and group restrictions in PHP applications?

When developing PHP applications, it is important to properly handle user permissions and group restrictions to ensure data security and access control. One common approach is to use role-based access control (RBAC) where users are assigned specific roles with corresponding permissions. This allows for granular control over who can access certain parts of the application and what actions they can perform.

// Example of RBAC implementation in PHP

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

// Check if user has permission to perform a certain action
function hasPermission($role, $permission) {
    global $roles;
    
    if (isset($roles[$role]) && in_array($permission, $roles[$role])) {
        return true;
    }
    
    return false;
}

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