How can PHP be used to prevent users from closing a window or navigating to another page without logging out or deleting sessions?

To prevent users from closing a window or navigating to another page without logging out or deleting sessions, you can use JavaScript to detect when the user tries to leave the page and trigger a confirmation dialog. This dialog can prompt the user to confirm if they want to leave the page without logging out. Additionally, you can use PHP to check if the user is logged in on each page load and redirect them to the login page if they are not logged in.

// Check if the user is logged in on each page load
session_start();
if(!isset($_SESSION['logged_in'])) {
    header("Location: login.php");
    exit();
}