How to increment a counter each page load (in PHP)?
11,413
Solution 1
It would be pretty simple to just use $_SESSION
data to store how many pages an individual has viewed.
$_SESSION['pageviews'] = ($_SESSION['pageviews']) ? $_SESSION['pageviews'] + 1 : 1;
Solution 2
The simplest method would be to use PHP's session storage.
session_start();
@$_SESSION['pagecount']++;
PHP automatically sends the user a session cookie, and transparently stores the content of $_SESSION in a flat file associated with this cookie. You don't really need to roll your own solution for this problem.
Author by
meleyal
Updated on June 14, 2022Comments
-
meleyal almost 2 years
I want a certain action to happen when a user has visited X pages of a site
Do I have to store the counter externally (in a txt file or db)?
I can't think of a way to set the counter to 0, then increment it each page load. The counter would always get reset to 0, or am I missing something obvious?
-
Frank Farmer almost 15 yearsPutting the count in the URL doesn't work if the user hits the back button or opens multiple tabs, and causes duplicate content issues for search-engine purposes.
-
Josh Curren almost 15 yearsTrue. I didnt think about that.
-
Frank Farmer almost 15 yearshtxt: make sure you're calling session_start() before attempting to use $_SESSION
-
Luc M almost 15 yearshtxt: session_start() must be call before any data outputed. Data may be header sent from server, some echo or print in your code.
-
meleyal almost 15 yearsCould you do something similar with cookies? I'm using Wordpress, which seems to be eating my session variables