Count post view when user open any post

One way to stop this would be to remember if this visitor has seen this page in the last x minutes. You can tackle that in multiple ways:

  • Use a cookie
  • Save visitor IP
  • Use sessions

Personally, I find using sessions just for counting pages is a bit silly.

Cookies can be a good solution, and you can set an expiration time if you want to re-count the same user after some time (even if that is a page refresh). But perhaps you don’t want to inflict cookies on your visitors for this (also, there are European regulations on cookies).

Saving the IP address is not fool-proof (visitors can use proxy servers or dynamic IP addresses assigned by their ISP), but it is still a good solution for a simple counter. Since you already have a function to count your users, you could simply add their IP address while you’re at it.

If you want this IP logging to expire after a certain time, like cookies can, you will also need to add a time stamp of when you added this IP address. You could then do two things:

  • Your counter script could check the timestamps in the log and ignore the entries which are older than x minutes.
  • You could set up a cronjob for a separate script which deletes entries from the log which are older than x minutes.

The latter is preferable if your log grows quickly.

tech