In PHP, what is the recommended approach for handling session variables within a login authentication process?

When handling session variables within a login authentication process in PHP, it is recommended to set session variables upon successful authentication and destroy them upon logout to ensure security. This helps to keep track of the user's authentication status and prevent unauthorized access to restricted areas of the website.

// Start the session
session_start();

// Check if the user is authenticated
if ($authenticated) {
    // Set session variables
    $_SESSION['user_id'] = $user_id;
    $_SESSION['username'] = $username;
} else {
    // Redirect or display an error message
}

// Upon logout, destroy session variables
session_unset();
session_destroy();