What are some potential pitfalls of using onunload event to invalidate sessions in PHP?

Using the onunload event to invalidate sessions in PHP can be unreliable as it relies on the user's browser to trigger the event when the page is closed or refreshed. A more secure and consistent approach is to use a server-side method, such as setting a session timeout and checking it on each page load.

// Check session timeout on each page load
session_start();

if(isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 1800)) {
    // Session has expired, destroy it
    session_unset();
    session_destroy();
}

$_SESSION['last_activity'] = time();