Due to updates, over time, that have been made to the site and the age of this article, this post may not display correctly. In particular images may be missing or product reviews display incorrectly.

If this is the case and you'd particularly like me to fix it, then please reach out to me on Twitter.

I often wondered how sites detected the number of users online. After some digging I’ll admit to be no closer to the answer. The problem is that once a page is delivered to someone you have no idea what they’re doing unless, and if, they then do something – go to another page of yours, click a button, etc. They could have immediately left the site and gone elsewhere… you simply don’t get back the level of interaction that would tell you this.

So my solution was based on simple maths. Using Google Analytics and the like I work out how long an average user spends looking at a page on the site. Let’s say it’s 90 seconds.

I’m using PHP and MySQL for this example. So, create a new table named users_online and create two fields for it – the first named timestamp and the second ip_address.

With your database already open execute the following PHP, pre-setting the variable $online_seconds with the figure we discussed a couple of sentences ago (in my example, 90). This should be at the top of each page.

This will add the period of time (90 seconds) to the current timestamp and insert a row into the table with that as a “timeout”. We then delete any rows where this timeour has now passed. Finally, we read the number of distinct IP addresses – this is the number of users currently online and is returned as $user_num.

How does this work? Well, the idea is that after 90 seconds if the user hasn’t moved onto another page or refreshed the current one then they’re gone. If they do, a new row with their IP address is created and they’re counted once more as still being active. Quite simple really. Possibly not the most accurate but without using host-side JavaScript, for instance, then I’m not sure how you would.

If nothing else it’s handy to have an idea as to how many people are online before you upgrade your site and potentially break it 😉