How can PHP be used to automatically log a user out of their account when they leave the page?

When a user leaves a page without logging out, their session can remain active, posing a security risk. To automatically log a user out when they leave the page, we can use JavaScript to detect when the user navigates away and then send a request to a PHP script that destroys the session.

<?php
// logout.php

session_start();
session_destroy();
echo "You have been logged out.";
?>