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.

Share:
11,413
meleyal
Author by

meleyal

Updated on June 14, 2022

Comments

  • meleyal
    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
    Frank Farmer almost 15 years
    Putting 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
    Josh Curren almost 15 years
    True. I didnt think about that.
  • Frank Farmer
    Frank Farmer almost 15 years
    htxt: make sure you're calling session_start() before attempting to use $_SESSION
  • Luc M
    Luc M almost 15 years
    htxt: session_start() must be call before any data outputed. Data may be header sent from server, some echo or print in your code.
  • meleyal
    meleyal almost 15 years
    Could you do something similar with cookies? I'm using Wordpress, which seems to be eating my session variables