Search code examples
phpjavascriptclientheartbeat

"Heartbeats" from client to server in PHP/JS


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.

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.

How does one accomplish this using php? I am running XAMPP at the moment. Any help would be much appreciated.

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.

Edit 2: isLoggedIn() is just helper function that checks to see if a session boolean variable ($_SESSION['is_logged_in')) is set.

Edit Final: 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.

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.

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

Here is a code snippet for a better explanation

Server Side:

function checkBeats()
{
    while(isLoggedIn())
    {
        // it's been > 30 secs since last heartbeat
        if((time() - $_SESSION['heartbeat']) > 30)
        {
            logout();
            break;
        }
    }
}

Solution

  • What i usually do is call a php file using javascript (jQuery) and update a database or whatevery you like. This question might answer yours: Whats the easiest way to determine if a user is online? (PHP/MYSQL)