What are some best practices for implementing a logout function in PHP to ensure accurate tracking of user sessions?

When implementing a logout function in PHP, it is important to ensure that the user session is properly destroyed to prevent unauthorized access to the account. This can be achieved by clearing the session data and destroying the session cookie. Additionally, it is good practice to redirect the user to a login page after logging out to prevent any further access to restricted areas.

<?php
session_start();

// Unset all session variables
$_SESSION = array();

// Destroy the session cookie
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Destroy the session
session_destroy();

// Redirect to the login page
header("Location: login.php");
exit;
?>