Search code examples
phpjqueryheartbeat

Counting the Number of Online Users Using jQuery Heartbeat (or PHP)


I am currently using this php code to count the number of the users currently online:

$session_id = session_id();
$time_stamp = time();
$time_limit = $time_stamp - 300;        //   We give the session only 5 minutes if it exists
$result = $this->select("SELECT * FROM `online_visitors` WHERE `session_id`='$session_id' LIMIT 1");
if (!mysql_num_rows($result)) {
    $tb_col[0] = "visitor_ip";
    $tb_col[1] = "country";
    $tb_col[2] = "session_id";
    $tb_col[3] = "time_stamp";
    $tb_col[4] = "last_time_stamp";
    $tb_data[0] = "'" . $this->visitor_ip . "'";
    $tb_data[1] = "'" . $this->visitor_country . "'";
    $tb_data[2] = "'" . $session_id . "'";
    $tb_data[3] = "'" . $time_stamp . "'";
    $tb_data[4] = "'" . $time_stamp . "'";
    $this->insert("`online_visitors`", $tb_col, $tb_data);
} else {
    $this->update("`online_visitors`", "`visitor_ip`='$this->visitor_ip', `country`='$this->visitor_country', `last_time_stamp`='$time_stamp'", "`session_id`='$session_id'");
}

$this->delete("`online_visitors`", "`last_time_stamp`<'$time_limit'");

But it does not update in real time. I want to check the number of users every 30 seconds. I may also want to connect this table to the jQuery heartbeat function, so I know more reliably how many users are currently online.

Am I approaching this properly? Any tips for how to achieve this in jQuery (I'm not very good with it)? Or can my approach be improved?

I also want to improve my php code


Solution

  • You can also do this the other way around: instead of updating the time via ajax, you assume that the user is online until he leaves the page or closes the browser. In this case you use ajax to set the user as offline and execute it when browser fires onbeforeunload. In rare cases (power outage, system crash) this event will not be fired, so its a good idea to check also when the last update was made in case you have a floating user.