What best practices should be followed when distributing rights or permissions to users in a PHP application?

When distributing rights or permissions to users in a PHP application, it is important to follow best practices to ensure security and proper access control. One common approach is to use role-based access control (RBAC), where users are assigned roles and permissions are associated with those roles. This helps in managing permissions at a higher level and simplifies the process of granting or revoking access.

// Example code snippet for implementing role-based access control in a PHP application

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

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

// Example usage
$userRole = 'admin';
$userPermission = 'delete';

if (hasPermission($userRole, $userPermission)) {
    echo 'User has permission to delete.';
} else {
    echo 'User does not have permission to delete.';
}