How can session variables be effectively used to manage user login status in PHP?

Session variables can be effectively used to manage user login status in PHP by storing a unique identifier (such as user ID) in a session variable upon successful login, and checking for the presence of this session variable on protected pages to determine if the user is logged in. This approach ensures that only authenticated users can access certain parts of the website.

// Start the session
session_start();

// Upon successful login, store user ID in a session variable
$_SESSION['user_id'] = $user_id;

// On protected pages, check if user is logged in
if(isset($_SESSION['user_id'])) {
    // User is logged in, allow access to content
} else {
    // User is not logged in, redirect to login page
    header("Location: login.php");
    exit();
}