How can a PHP session be invalidated when a user closes the page?

When a user closes the page, the PHP session should be invalidated to ensure the user is logged out and their session data is cleared. This can be achieved by setting a session cookie with a short expiration time, so that when the user closes the page, the cookie expires and the session is automatically destroyed.

// Set session cookie with short expiration time
session_start();
setcookie(session_name(), session_id(), time()-3600, '/');
session_destroy();