What best practice can be recommended for ensuring proper session variable handling in PHP login scripts, particularly when using automatic redirection?

When using automatic redirection in PHP login scripts, it is important to properly handle session variables to ensure security and functionality. One best practice is to always start the session at the beginning of the script, before any output is sent to the browser. This ensures that session variables are available throughout the script execution. Additionally, make sure to unset or destroy session variables once they are no longer needed to prevent unauthorized access.

<?php
session_start();

// Check if the user is logged in
if(!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Once the session variables are no longer needed, unset or destroy them
unset($_SESSION['user_id']);
session_destroy();
?>