What are the best practices for handling session variables in PHP to ensure consistent login status across multiple pages?

To ensure consistent login status across multiple pages in PHP, it's important to properly handle session variables. This can be achieved by starting the session on every page where session variables are needed, checking for the existence of a specific session variable to determine if a user is logged in, and setting/unsetting session variables accordingly based on login/logout actions.

// Start the session on every page where session variables are needed
session_start();

// Check if the session variable 'logged_in' is set to determine if the user is logged in
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
    // User is logged in
} else {
    // User is not logged in
}

// Set session variable on login
$_SESSION['logged_in'] = true;

// Unset session variable on logout
unset($_SESSION['logged_in']);