What are the best practices for using sessions in PHP to manage user authentication and access control?

Using sessions in PHP is a common way to manage user authentication and access control. To ensure security, it is important to properly set up and manage sessions, including setting session variables to store user authentication information and checking these variables on each page to control access.

// Start the session
session_start();

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

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