Check if user closed the page in PHP?

前端 未结 9 1938
孤城傲影
孤城傲影 2020-12-22 06:04

I made a chat using PHP and JavaScript chat and there is a disconnect button which removes user from the chat removing him from user list first. But if the user closes brows

相关标签:
9条回答
  • 2020-12-22 06:42

    If you can't modify the JS code for some reason, there really is little you can do. Only thing you can do with PHP is to check if there's been for example over 15 minutes from the last activity, the user has left. But this is in no way a smart thing to do – a user might just sit and watch the conversation for 15 minutes.

    Only proper way to do is using AJAX polling in set intervals if you want to do it reliably.

    You noted that a user polls the server for new messages constantly, can't you use that to detect if user has left?

    0 讨论(0)
  • 2020-12-22 06:42

    Maintain a list of active users on the server, as well as the last time they connected to the chat to request new messages.

    When a user connects to check for messages update their time.

    Whenever your code runs iterate through this list and remove users who haven't connected in too long.

    The only failure is that if the number of users in the channel drops to zero, the server wont notice until someone comes back.

    0 讨论(0)
  • 2020-12-22 06:42

    To address your edit, you can ignore client termination by using ignore_user_abort.

    0 讨论(0)
  • 2020-12-22 06:43

    Using javascript u can do the following :

    <script type="text/javascript">
    
    window.onunload = unloadPage;
    
    function unloadPage()
    {
     alert("unload event detected!");
    }
    </script>
    

    Make the necessary ajax call on the unloadPage() function to ur PHP Script

    0 讨论(0)
  • 2020-12-22 06:44

    The answers to all the questions asked by the OP are covered in the section in the manual about connection handling:

    http://uk3.php.net/manual/en/features.connection-handling.php

    No Ajax.

    No Javascript.

    No keep alives.

    C.

    0 讨论(0)
  • 2020-12-22 06:48

    Request a PHP script that goes a little something like this, with AJAX:

    register_shutdown_function("disconnect_current_user");
    header('Content-type: multipart/x-mixed-replace; boundary="pulse"');
    
    while(true) {
       echo "--pulse\r\n.\r\n";
       sleep(2);
    }
    

    This way, you won't constantly be opening/closing connections.

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