You'll need a Javascript function to make some sort of submission to the server, and tie it to the browser's onUnload handler.
...oops, my Javascript knowledge has just gone -zot-, so I can't write the function. But it would submit to or request the PHP script you want run.
In short, this is more a Javascript question. And like I said, I'm drawing a blank on how to write Javascript right now.