How can sessions be used to manage user authentication in PHP?

Sessions can be used to manage user authentication in PHP by storing the user's authentication status (such as logged in or logged out) in a session variable. When a user logs in, their authentication status is set in the session, and when they log out, the session variable is unset. This allows the application to check the user's authentication status on each page load to determine if they have access to certain resources.

// Start the session
session_start();

// Check if the user is logged in
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true){
    // User is authenticated, allow access to resources
} else {
    // User is not authenticated, redirect to login page
    header("Location: login.php");
    exit();
}