简体   繁体   English

如何在每个页面加载时增加一个计数器(在PHP中)?

[英]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 我想要在用户访问网站的X页面时发生某种操作

Do I have to store the counter externally (in a txt file or db)? 我是否必须在外部存储计数器(在txt文件或数据库中)?

I can't think of a way to set the counter to 0, then increment it each page load. 我想不出将计数器设置为0的方法,然后在每次页面加载时增加它。 The counter would always get reset to 0, or am I missing something obvious? 计数器总是会重置为0,或者我错过了一些明显的东西?

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

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

The simplest method would be to use PHP's session storage . 最简单的方法是使用PHP的会话存储

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. PHP自动向用户发送会话cookie,并将$ _SESSION的内容透明地存储在与此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. 简短的回答是肯定的,你必须在外部保存它,因为php(默认情况下)具有零内存持久性策略。 This means basically that once your php script has run there's nothing left in memory. 这基本上意味着一旦你的php脚本运行,内存中就没有任何东西了。

For a low traffic site you might want to think about a simple txt file where you read, increment and write. 对于流量较低的站点,您可能需要考虑一个简单的txt文件,您可以在其中读取,增加和写入。 For a higher traffic site a very simple mysql table might work. 对于更高流量的站点,一个非常简单的mysql表可能会起作用。

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. 或者您只是想跟踪访问者看到的页面数量,并在查看的第x页上做一些特别的事情。

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语句检查它是否已经设置;

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. 您还可以使用get方法将计数放入URL中,这样您就不必将计数写入文件或数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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