How can I execute PHP code on page close?

前端 未结 6 1913
心在旅途
心在旅途 2021-01-06 04:01

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 st

相关标签:
6条回答
  • 2021-01-06 04:04

    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
         }
      })
    }
    
    0 讨论(0)
  • 2021-01-06 04:12

    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 :-)

    0 讨论(0)
  • 2021-01-06 04:12

    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

    0 讨论(0)
  • 2021-01-06 04:16

    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?

    0 讨论(0)
  • 2021-01-06 04:20

    Use the Body attribute onunload

    http://www.htmlcodetutorial.com/document/_BODY_onUnload.html

    0 讨论(0)
  • 2021-01-06 04:26

    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.

    0 讨论(0)
提交回复
热议问题