How can sessions be effectively managed in PHP to handle user authentication for a login system?

Sessions can be effectively managed in PHP to handle user authentication for a login system by storing user credentials in session variables upon successful login and checking these session variables on subsequent pages to determine if the user is authenticated. This allows the system to keep track of the user's login status throughout their session.

// Start the session
session_start();

// Check if user is logged in
if(isset($_SESSION['user_id'])){
    // User is authenticated, perform actions
    echo "Welcome, ".$_SESSION['username']."!";
} else {
    // Redirect to login page
    header("Location: login.php");
    exit();
}