How can I execute PHP code on page close?
I am trying to find a method to execute some PHP code once a user closes the page. In my application, once the user closes or navigates away from the page the server will s开发者_运维百科tate the user as 'Offline' in the database. This requires the code to know when the user has navigated away from the page. My application also has an endless load (i.e. it will sleep until the user closes the page).
Reliably sending an event when the user closes the page is close to impossible. There is the onbeforeunload
event that could do an Ajax call, but that could fail, not be executed for security reasons, or not be executed at all because the user has JavaScript turned off.
This is usually done through session timeouts: It is checked when a request for a certain session was last made. If it was longer than x minutes ago, the session is treated as expired. Is that not an option?
Page requests are stateless, meaning you'll never have a 100% working detection method to determine if someone has left the page. You can try to catch the page unloading, but this isn't 100% accurate. You could also try as @Nayena mentioned with AJAX, but this is less than ideal.
Your best bet is to do like most common sites do, use "last activity within N minutes" as an indicator and not try to catch when they navigate away or close the page.
If you put in a ajax script that refreshes after 5-10 seconds, you can update the last updated stamp via the php file that the ajax request calls, and if its older than 10 seconds it went offline. That could certainly be a cleaner solution :-)
If you can use Javascript and JQuery, use 'window.onclose' and then an Ajax call to do whatever you want using PHP:
Capture event onclose browser
// Javascript code
window.onclose = closing;
function closing(){
$.ajax({
url: 'yoururl.php',
data: yourdata,
success: function(content){
// empty
}
})
}
Use the Body attribute onunload
http://www.htmlcodetutorial.com/document/_BODY_onUnload.html
Simply set ignore_user_abort(true)
then enter an infinite while loop of
while (!connection_aborted()){
// do nothing ...
}
//after the while loop :
some_function_to_say_that_the_user_is_offline();
but be carefull , whenever the user navigates out of the page , the function WILL be executed .
EDIT : and the progress bar of the browser will be like "downloading ..." forever ...
Edit 2 : check also http://www.php.net/manual/en/function.register-shutdown-function.php
精彩评论