What is the recommended method to handle logout in a session-based login system using PHP?

In a session-based login system using PHP, the recommended method to handle logout is to destroy the session data associated with the user when they choose to logout. This ensures that the user is effectively logged out and their session is terminated.

<?php
session_start();

// Check if user is logged in
if(isset($_SESSION['user_id'])) {
    // Unset all session variables
    $_SESSION = array();

    // Destroy the session
    session_destroy();

    // Redirect to login page or any other desired page
    header("Location: login.php");
    exit;
} else {
    // Redirect to login page if user is not logged in
    header("Location: login.php");
    exit;
}
?>