简体   繁体   中英

How to increment a counter each page load (in PHP)?

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?

使用$_SESSION数据来存储个人查看的页数非常简单。

$_SESSION['pageviews'] = ($_SESSION['pageviews']) ? $_SESSION['pageviews'] + 1 : 1;

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.

You can start a session when the user first gets to your page, and then increment the value each time the user reloads/visits subpages. Another way to do it, is to have a hidden field on every page, and retrieve its value, increment it and post it to the new page.

<input type="hidden" value="2" id="blabla" />

The short answer is yes, you do have to save this externally because php (by default) has a zero memory persistence policy. This means basically that once your php script has run there's nothing left in memory.

For a low traffic site you might want to think about a simple txt file where you read, increment and write. For a higher traffic site a very simple mysql table might work.

Do you already have a way of determining who a user is (like a username & password), even if they leave the site and come back another day? Or are you just interested in tracking the number of pages a visitor sees, and doing something special on the xth page viewed.

If it's the second, you already have a session variable where you can store the counter.

$_SESSION['views'] = $_SESSION['views'] + 1
if($_SESSION['views'] == x) ...

you would use an if statement to check if it is already set;

if( isset($count) )
{
   $count = $count + 1;
}
else
{
   $count = 1;
}

You can also use the get method to put the count in the URL so that you dont have to write the count to a file or database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM