tags:

views:

41

answers:

3

I need to implement "viewed" system.

How it can be done, so that pressing F5 would not increase viewed number for more than 1 per user?

SO also has such system.

Cookies, sessions, db? How it is usually done?

+3  A: 

You will need a combination of technologies here. Each user needs to be identified uniquely (using sessions, cookies, whatever works best in your scenario). From there, you will need to be maintaining a database of hits for an item with the user's unique key (stored in their cookie or session or whatever).

When the user accesses the page, check the database to see if that user's unique key already has a hit on that page. If not, add it. Regardless, once done, pull the total number of hits that the item has had from the database. Tahdah.

Matchu
db should record all users unique keys that viewed this page?
Qiao
Mhm. A row consists of an ID for the page you are tracking, and the unique key of the user who visited it.
Matchu
+1  A: 

Just store in your database user_id, resource_id (eventually timestamp) and before you increase viewed value check whether SQL like this:

SELECT COUNT(*) FROM ... WHERE user_id = ? AND resource_id = ? (AND timestamp > NOW() - 7 DAYS or sth)

doesn't return 1.

Crozin
you mean separate table for viewed needs?
Qiao
Yes. (+10 characters to add comment :])
Crozin
A: 

This depends a lot on the situation. For example, if each user is logged in with a user ID, it would be very different then if you are doing a splash page where users are not expected to be logged in.

I will assume you are in the latter category, and that users are not logged in to your page. If this were the case, I would recommend setting a cookie using the setcookie command, this could be accomplished like this:

if (empty($_COOKIE['hasViewed'])) {
    //increment the total number of views in the
    //database or wherever we are storing it.
    $viewer->incrementViews();
}
//make sure they have a cookie for next time
setcookie("hasViewed", "1", time() + 60*60*24*30);

Note that in this example, the user would be able to cause your view to increment again if they haven't seen the page in 30 days.

Luke Magill
but if there is many pages needed to be viewed...
Qiao
Include a hash of the page name (or some other way of identifying the page) in the cookie.
Blair McMillan
@QiaoIf that is the case, I would recommend storing it in the session, because while you could handle it by sending out cookies, they will become unwieldy after a while. Make sure that your sessions don't expire to early however, otherwise you will have to set up a more complex solution.
Luke Magill