What are best practices for securely logging out a user in a PHP session-based login system?

When logging out a user in a PHP session-based login system, it is important to destroy the session variables and regenerate the session ID to prevent session fixation attacks. Additionally, clearing any cookies related to the session can further enhance security.

// Start the session
session_start();

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

// Destroy the session
session_destroy();

// Regenerate the session ID
session_start();
session_regenerate_id();

// Clear any cookies related to the session
setcookie(session_name(), '', time() - 3600, '/');

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