Track Page Views using PHP

2019-04-10 01:34发布

问题:

I'm looking for a way to track the number of visits to a page, without counting duplicates (like someone hitting refresh several times) and I'd like to figure out the best way to do it without keeping track of every single IP address to view the page. Perhaps a cookie? Any other suggestions?

回答1:

Either use Webalizer to analyse your logfiles or use Google Analytics to track those metrics for you or - if you are looking for an extendable and self hosted solution, try Piwik:

Piwik is a downloadable, open source (GPL licensed) real time web analytics software program. It provides you with detailed reports on your website visitors: the search engines and keywords they used, the language they speak, your popular pages… and so much more.

In any case, there is no reason to reinvent the wheel here. Also, the software mentioned above is only a tiny fraction of web analysis tools out there.



回答2:

Cookies are a good way to achieve this, however you have to keep in mind that users could have disabled cookies... When a user visits your page, just check if your cookie is already present, if not, count++ :)



回答3:

A cookie will fit. Just at each page view you check if it is set. If so, don't count it. Otherwise, count it and set the cookie.

You will have problems with people not having cookies enabled or cleaning them out after each visit. You should pair this approach with PHP sessions: instead of doing the process on each page view, do it only once, on session start. This will at least avoid counting visits within a single session.

All this is you want to store everything client-side. If you were server-side, you could use IP addresses, or pair them with the user agent string.

Or, just use google analytics...



回答4:

You mentioned in one of the other comments that you are already using Google Analytics, so you should be able to do the following:

Create a custom report with "Page" as a Dimension and "Unique Visitors" as a metric. This will tell you how many unique Visitors there were for all of your pages for whatever time frame.



回答5:

Store/increment a key/value with redis or memcache, then run a cron job to store values for page/user every x-amount of minutes. Don't need to get complicated with things.