How can PHP sessions be effectively utilized to ensure user authentication and access control in a web application?

To ensure user authentication and access control in a web application using PHP sessions, you can store user credentials in a session variable upon successful login and check for this variable on protected pages to determine if the user is authenticated. Additionally, you can set different user roles or permissions in the session to control access to specific areas of the application.

<?php
session_start();

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

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

// Protected page content here
?>