How can PHP sessions be effectively used to store and manage user roles and permissions for authentication purposes?
To effectively use PHP sessions to store and manage user roles and permissions for authentication purposes, you can store the user's role and permissions in the session variable upon successful login. Then, on each restricted page, you can check the user's role and permissions stored in the session to determine if they have access to that specific page.
// Start the session
session_start();
// Upon successful login, store user role and permissions in session
$_SESSION['user_role'] = 'admin';
$_SESSION['permissions'] = ['view_users', 'edit_users', 'delete_users'];
// Check user role and permissions on restricted page
if ($_SESSION['user_role'] !== 'admin' || !in_array('view_users', $_SESSION['permissions'])) {
// Redirect user to unauthorized page
header('Location: unauthorized.php');
exit();
}