How can PHP sessions be effectively utilized for managing user authentication and authorization?

To effectively utilize PHP sessions for managing user authentication and authorization, you can store user credentials in session variables upon successful login and check these variables on protected pages to ensure the user is authenticated. Additionally, you can set session variables to control user roles and permissions for authorization purposes.

// Start the session
session_start();

// Check if user is logged in
if(isset($_SESSION['user_id'])){
    // User is authenticated
    // Check user role for authorization
    if($_SESSION['user_role'] == 'admin'){
        // User has admin privileges
    } else {
        // User does not have admin privileges
    }
} else {
    // Redirect user to login page
    header("Location: login.php");
    exit();
}