PHP - 页面被查看的次数

I want PHP to be able to echo the amount of times the page has been viewed. Being a server side scripting language I'm fairly confident there's a way.

This is what I'm thinking...

main.php

<body>
<?php
include("views.php");
$views = $views + 1;
echo $views;
?>
</body>

views.php

<?php $views = 0; ?>

This works, but does not update. (It will display 1, but will not keep counting upon refresh.)

The problem is that the variable $views does not persist from view to view. In fact, the next time someone comes back to your website $views would have been reset to 0. You'll need to take a look at some form of persistence to store the total number of views.

One way that you can accomplish this is to use a database or via a file. If you are using files, you can do the following inside of your views.php file.

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;

You will need to store the data somewhere. Variables do not keep their state between requests. $views = 0 always means $views = 0, regardless of whether that variable is being included or not.

Write the number of views to a file (file_put_contents, file_get_contents) or to a database to store them permanently.

When you refresh the page, the state is not saved. This $views is set to 0 everytime you begin, and gets incremented by 1.

To increment the count and save the value, you will need to persist the number by either using a database or a file.

Great idea will be to use a database like MySQL. There are a lot of articles over the Internet how to set it up and use with PHP.

What you would probably want to do - update a page row in 'views' every time page is accessed. Simplest way is something like this:

<?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'");