How can PHP sessions be effectively utilized to manage user authentication and access control in a website with user profiles and comments?

To manage user authentication and access control in a website with user profiles and comments, PHP sessions can be effectively utilized by storing user information such as user ID and role after successful login. This information can then be used to determine whether a user has the necessary permissions to access certain pages or perform specific actions on the website.

// Start a session
session_start();

// Check if user is logged in
if(isset($_SESSION['user_id'])) {
    // User is logged in, fetch user information from database
    $user_id = $_SESSION['user_id'];
    
    // Check user role to determine access level
    $user_role = $_SESSION['user_role'];
    
    // Example: Only allow admins to access admin panel
    if($user_role == 'admin') {
        // Display admin panel content
    } else {
        // Redirect user to homepage or show access denied message
    }
} else {
    // User is not logged in, redirect to login page
    header('Location: login.php');
    exit();
}