[英]PHP - How many times the page has been viewed
我希望PHP能够回显页面被查看的次数。 作为服务器端脚本语言我非常有信心有一种方法。
这就是我的想法......
main.php
<body>
<?php
include("views.php");
$views = $views + 1;
echo $views;
?>
</body>
views.php
<?php $views = 0; ?>
这有效,但不会更新。 (它将显示1,但不会继续计数刷新。)
问题是变量$views
不会从视图到视图持久存在。 事实上,下次有人回到你的网站时, $views
会被重置为0.你需要看看某种形式的持久性来存储视图总数。
您可以实现此目的的一种方法是使用数据库或通过文件。 如果您使用的是文件,则可以在views.php文件中执行以下操作。
views.php
$views = 0;
$visitors_file = "visitors.txt";
// Load up the persisted value from the file and update $views
if (file_exists($visitors_file))
{
$views = (int)file_get_contents($visitors_file)
}
// Increment the views counter since a new visitor has loaded the page
$views++;
// Save the contents of this variable back into the file for next time
file_put_contents($visitors_file, $views);
main.php
include("views.php");
echo $views;
您需要将数据存储在某处。 变量不会在请求之间保持状态。 $views = 0
总是表示$views = 0
,无论是否included
该变量。
将视图数file_put_contents
文件( file_put_contents
, file_get_contents
)或数据库以永久存储它们。
刷新页面时,不会保存状态。 每次开始时,此$views
都设置为0,并增加1。
要增加计数并保存值,您需要使用数据库或文件来保留数字。
好主意是使用像MySQL这样的数据库。 互联网上有很多文章如何设置和使用PHP。
您可能想要做什么 - 每次访问页面时更新“视图”中的页面行。 最简单的方法是这样的:
<?php
/* don't forget to connect and select a database first */
$page = 'Home Page'; // Unique for every page
mysql_query("UPDATE views SET num = num + 1 WHERE page = '$page'");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.