问题
I want to get and display how many times a page is viewed, just like stackoverflow.
How to do it by php? Thanks!
回答1:
if (file_exists('count_file.txt')) { $fil = fopen('count_file.txt', r); $dat = fread($fil, filesize('count_file.txt')); echo $dat+1; fclose($fil); $fil = fopen('count_file.txt', w); fwrite($fil, $dat+1); } else { $fil = fopen('count_file.txt', w); fwrite($fil, 1); echo '1'; fclose($fil); } ?>
For any "decent" counter I would recommend to use a database (mysql, redis ) and trace IP address to have even deeper analytics (e.g how many unique visits, where they are comming from etc)
回答2:
You will need to store that information somewhere, which isn't really something that you can do with only PHP.
Most commonly, this is stored in a database. The simplest solution is a single database row per page that you wish to track with a column for remembering the view count. You would increment this column each time the page is loaded.
Slightly more complicated, but far more useful, would be to add a database row on each page load, noting the page, time, and any other information that you might find useful.
Another simple way to capture this information would be to install an analytics package on your site. Something like Google Analytics, which is free. But, it isn't particularly tailored to displaying page views, simply capturing them.
来源:https://stackoverflow.com/questions/6901524/how-to-get-page-view-data-like-stackoverflow