This is one of the most fundamental ideas in PHP programming. It is important for you to understand.
For PHP to react to something the user does, an HTTP request must be made to the server.
JavaScript can trigger an HTTP request in a number of ways: [1] using the XMLHttpRequest object (AJAX), [2] inserting a tag which requires an external resource (<img>, <link>, <script>, <iframe>, etc.), [3] changing the src or href of such a tag, [4] (I could have overlooked something). Anyway, the point is that there must be a separate request.
I see you have discovered this already, but I will post my example because I had it prepared already and I think the comments will be helpful.
This example logs the current server time into a file (on the server, of course) when you close the browser window.
page.html - The first request is for this HTML document. When the page loads, your browser makes a second request, for close.js.
Code: Select all
<!DOCTYPE html>
<html>
<head>
<title>Close</title>
<script type="text/javascript" src="close.js"></script>
</head>
<body>
<p>Close me.</p>
</body>
</html>
close.js - When you close the page, JavaScript inserts an image tag. When the image is inserted, your browser makes its third request, for ping.php.
Code: Select all
window.onunload = function () {
var img = document.createElement('img');
img.src = 'ping.php';
document.body.appendChild(img);
}
ping.php
Code: Select all
<?php
file_put_contents('ping.txt', date('Y-m-d H:i:s'));