Reputation: 693
I'm not sure what would be the best way to do this, but I need to be able to show the number og guests that are viewing the current page a visitor is viewing. No who but how many.
What would be the easiest approach to do something like this? is is possible to do this without a database, but maybe with a javascript or PHP?
The output would be "There are XX people viewing this page".
Edit: Could this be done by showing the number of Unique Visitors the last 15 minutes? I wouldn't be 100% accurate but would work for my purpose
Upvotes: 3
Views: 6058
Reputation: 5889
I think the easiest way for live tracking of visitors would be to let the client of each visitor send every x seconds an ajax request to a script of you and you keep tracking of all session ids / pages in a table or text file. If a session id not posted for a certain time from a specific page remove it.
If you do it with a database. Use a table like
tracking
--------
sessionid (PK)
pageID (or pageURI)
last_seen (timestamp)
Then you can query on that table to get the amount of (more or less) current users visiting that page.
SELECT COUNT(*) visitors FROM tracking WHERE last_seen < DATE_SUB(NOW(), INTERVAL 30 SECONDS) GROUP BY pageID
But this does not work if the user has javascript disabled so its not a 100% exact solution.
Upvotes: 1
Reputation: 2890
HTTP is a stateless protocol, there's no way to determine how many visitors are currently "online", because there simply is no way to identify unique users except for an explicit login. It's all based on estimations (for example the amount of requests from different IPs in the last 10 minutes) and as useless as a hitcounter for a visitor. The number of currently browsing users or page hits says absolutely nothing about a site's quality.
The simpliest way is to write a script that inserts (or updates) the IP and Time/date in a DB table. Then count the # of unique IP's and puge the old one's. Most sites look at a 10 min. interval for this purpose; given the nature of HTTP.
Call [the file] "userCount.php" or somthing and include it at the top of your header so it's called on every page hit.
// ** Begin userCount.php **//
$timestamp=time();
// 10 minutes of timeout
$timeout=$timestamp-6000;
// REPLACE instead of INSERT
mysql_query("REPLACE INTO online (time,ip) VALUES
('$timestamp','$REMOTE_ADDR')
WHERE ip = '$REMOTE_ADDR')";
// purge all old users
mysql_query("DELETE FROM online WHERE time < $timeout");
// delete my own ip adress from statistic
mysql_query("DELETE FROM online WHERE ip = 'xxx.xxx.xxxx.xxxx'");
$result=mysql_query("SELECT ip FROM online");
$user=mysql_num_rows($result);
echo $user;
// ** End userCount.php **//
This should work.
Taken from Here
Upvotes: 2