I had to code an application at one point where it was absolutely necessary to detect when a user logged out by either clicking the logout button or by closing the window. The way I did it was with javascript's onUnLoad function and a pop-up window. In the body tag of my page I set onOnLoad to pop up a new window with my php code to log the user out. The php page that popped open also just automatically closed itself once it was finished.
main page
<body onUnLoad="window.open('title','logout.php');">
logout.php
<?php
//code to log the user out
?>
<html>
<body onload="window.close();">
</body>
</html>