How can PHP sessions be effectively used to manage user authentication and access control?

To manage user authentication and access control using PHP sessions, you can store user credentials in session variables upon successful login and then check these session variables on protected pages to determine if the user is authenticated. Additionally, you can use session variables to store user roles or permissions to control access to specific pages or functionalities.

// Start the session
session_start();

// Check if user is logged in
if(!isset($_SESSION['user_id'])) {
    // Redirect to login page
    header("Location: login.php");
    exit();
}

// Check user role for access control
if($_SESSION['user_role'] !== 'admin') {
    // Redirect to unauthorized page
    header("Location: unauthorized.php");
    exit();
}