Page Watch计数器

I'm developing a website which have many products. For every product I want to show a counter with the number of different users whom watched it.

I'm facing with the problem that there will be users logged in and others not, and that fact to avoiding to increment a 'watch' more than one time from the same user.

So, what's the best way to tackle this? How do I store the info?

For the simple solution, you can:

  1. To separate "view" users, you can count on user's IP.
  2. "View" info can be stored in a simple table product_view(id, product_id, view_ip, user_id)

This simply cannot be done for non-registered users. The closest thing you can do and in fact what web analytics services do in practice is to create a tracking cookie.

In its simplest form it looks something like this:

<?php
if (isset($_COOKIE["trackingId"])) {
    $uid = $_COOKIE["trackingId"];
} else {
    $uid = uniqid();
    setcookie("trackingId",$uid,2147483647);
}

Note that analytics sites will attempt to use information which may uniquely identify a user such as hardware capabilities which they receive, screen resolution etc.

Create a table:

Watched by users

productId, userId, trackingId

You can use this table to keep track of who's watching your product. Normal registered users will be stored with a userId. Non-registered users will be stored with their tracking id.

The advantage of this approach is that you can keep track of the same user using the same browser across sessions even if they change IP. The disadvantage is that as soon as the user clears their cookies you've lost this information.

You can refine your tracking mechanism by doing something like canvas fingerprinting instead of using uniqid but the thing to realise here is that there's no method which can uniquely identify a user forever and rightly so because a user should have the right to not be tracked.