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

To manage user authentication and access control in a web application using PHP sessions, you can store user credentials in the session variables upon successful login and check these variables on each page to determine if the user is authenticated. Additionally, you can use session variables to store user roles or permissions and restrict access to certain pages based on these roles.

// Start the session
session_start();

// Check if user is logged in
if(isset($_SESSION['user_id'])){
    // User is authenticated, allow access
    // You can also check user roles/permissions here
} else {
    // Redirect to login page
    header("Location: login.php");
    exit();
}