PHP execute code on page close

I am trying to find a method to execute some PHP code when the user closes the page. In my application, when a user closes or moves away from the page, the server will indicate the user as "offline" in the database. This requires the code to know when the user navigated from the page. My application also has an infinite load (i.e., it will sleep until the user closes the page).

Edit:

Thanks for answers. I decided to go with the Pekka session method, as this seemed the most logical for my application.

Greetings

+4
source share
6 answers

Reliably sending an event when the user closes the page is almost impossible. There is an onbeforeunload event that may make an Ajax call, but it may fail, fail for security reasons, or fail at all because the user has disabled JavaScript.

This is usually done through session timeouts: it is checked when the last request was made. If it was more than x minutes ago, the session is treated as expired. Isn't that an option?

+9
source

Page requests are stateless, meaning you will never have a 100% working discovery method to determine if someone has left the page. You can try to catch the page offload, but this is not 100% accurate. You can also try like @Nayena mentioned in AJAX, but it is less than ideal.

Itโ€™s best to do as most regular sites do, use the โ€œlast N minute actionโ€ as an indicator and not try to catch when they move or close the page.

+4
source

If you added an ajax script that is updated in 5-10 seconds, you can update the last updated print via the php file that called the ajax request, and if it is more than 10 seconds, it will be disconnected. This could certainly be a cleaner solution :-)

+3
source

If you can use Javascript and jQuery, use "window.onclose" and then call Ajax to do whatever you want using PHP:

Onclose browser event capture

 // Javascript code window.onclose = closing; function closing(){ $.ajax({ url: 'yoururl.php', data: yourdata, success: function(content){ // empty } }) } 
0
source

Just set ignore_user_abort(true) , then enter an infinite while loop

  while (!connection_aborted()){ // do nothing ... } //after the while loop : some_function_to_say_that_the_user_is_offline(); 

but be careful, whenever a user navigates from a page, the WILL function will be executed.

EDIT: and the progress bar of the browser will forever "load ..." ...

Edit 2: also check out http://www.php.net/manual/en/function.register-shutdown-function.php

0
source

Source: https://habr.com/ru/post/1337967/


All Articles