use*_*415 1 html javascript css php include
我希望 PHP 能够回显页面被查看的次数。作为服务器端脚本语言,我相当有信心有办法。
这就是我的想法...
main.php
<body>
<?php
include("views.php");
$views = $views + 1;
echo $views;
?>
</body>
Run Code Online (Sandbox Code Playgroud)
视图.php
<?php $views = 0; ?>
Run Code Online (Sandbox Code Playgroud)
这有效,但不更新。(它会显示 1,但刷新后不会继续计数。)
问题在于该变量$views不会在视图之间持续存在。事实上,下次有人回到您的网站时$views就会被重置为 0。您需要考虑某种形式的持久性来存储浏览总数。
实现此目的的一种方法是使用数据库或通过文件。如果您使用文件,则可以在views.php 文件中执行以下操作。
视图.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);
Run Code Online (Sandbox Code Playgroud)
main.php
include("views.php");
echo $views;
Run Code Online (Sandbox Code Playgroud)