Note that there are some explanatory texts on larger screens.

plurals
  1. PO"Heartbeats" from client to server in PHP/JS
    text
    copied!<p>I am trying create a small web application that allows a user to "login" and "logout." What I am currently having a problem with is allowing the client to send constant "heartbeats" or messages to the server to notify that it is still active.</p> <p>This is more of a logical question. What I want to do is have a while(1) loop in php that checks if n number of heartbeats have been skipped. I still want the client and server to be able to interact while this loop is going on (essentially I want the server to behave as if it has a separate "check_for_heartbeats" thread. </p> <p>How does one accomplish this using php? I am running XAMPP at the moment. Any help would be much appreciated.</p> <p>Edit: To clarify, what I want to do is be able to catch a browser close event even on instances where the window.unload event won't fire (e.g. a client gets disconnected from the internet). In this case, having a thread to monitor heartbeats seems to be the most intuitive solution, though I'm not sure how to make it happen in php. </p> <p>Edit 2: isLoggedIn() is just helper function that checks to see if a session boolean variable ($_SESSION['is_logged_in')) is set.</p> <p><strong>Edit Final:</strong> Okay, so I now understand exactly what the comments and responses were saying. So to paraphrase, here is the potential solution: Have Javascript code to send "heartbeats" to the server. The server will add a timestamp associated with these beats. Modify the database to hold these time stamps Query the entire "timestamps" table (more likely a 'users' table with a 'timestamp' attribute), and see if the difference between NOW and last timestamp is greater than some threshold. "Log off" any users passed this threshold.</p> <p>The only issue is if there is just one user logged in or if all users lose connection at the same time - but in these cases, no one else will be there to see that a user has lost connection.</p> <p>This is a combination of multiple responses, but I think chris's response takes care of the majority of the issue. Thank you to both chris and Alex Lunix for the helpful contributions. :D</p> <p>Here is a code snippet for a better explanation</p> <p>Server Side:</p> <pre><code>function checkBeats() { while(isLoggedIn()) { // it's been &gt; 30 secs since last heartbeat if((time() - $_SESSION['heartbeat']) &gt; 30) { logout(); break; } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload