Reputation: 33320
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?
Upvotes: 2
Views: 12357
Reputation: 39386
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.
Upvotes: 1
Reputation: 25470
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) ...
Upvotes: 0
Reputation: 24472
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;
Upvotes: 14
Reputation: 2016
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.
Upvotes: 0
Reputation: 5479
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" />
Upvotes: 0
Reputation: 10226
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.
Upvotes: -2