What are the best practices for checking session variables on each page in a PHP application?

To ensure session variables are properly checked on each page in a PHP application, it is important to start the session at the beginning of each page and verify the existence of specific session variables before using them. This helps prevent errors and ensures that the application functions correctly.

<?php
// Start the session
session_start();

// Check if the session variable is set
if(isset($_SESSION['user_id'])) {
    // Proceed with using the session variable
    $user_id = $_SESSION['user_id'];
} else {
    // Redirect to login page if session variable is not set
    header("Location: login.php");
    exit();
}