使用PHP访问没有数据库的计数器 [英] Visits counter without database with PHP
问题描述
我只有一个网页,我想跟踪它在不使用数据库的情况下被访问了多少次.
I have a single webpage and i would like to track how many times it's visited without using a database.
我考虑过XML,每次用户访问页面时都会更新文件:
I thought about XML, updating a file every time a user visits the page:
<?xml version='1.0' encoding='utf-8'?>
<counter>8</counter>
然后,我认为最好在一个单独的文件中声明一个PHP计数器,然后在用户每次访问该页面时对其进行更新.
Then i thought it could have been a better idea to declare a PHP counter in a separate file and then update it everytime a user visits the page.
counter.php
counter.php
<?php
$counter = 0;
?>
update_counter.php:
update_counter.php:
<?php
include "counter.php";
$counter += 1;
$var = "<?php\n\t\$counter = $counter;\n?>";
file_put_contents('counter.php', $var);
?>
这样,每次访问update_counter.php
时,counter.php
文件中的变量都会增加.
With this, everytime update_counter.php
is visited, the variable in the counter.php
file is incremented.
无论如何,我注意到,如果counter.php
文件具有$counter = 5
,并且恰好同时有1000位用户访问了update_counter.php
文件,则该文件将同时被读取1000次(因此值5
会在所有请求中读取),counter.php
文件将更新为值5+1 (=6)
而不是1005
.
Anyway, i noticed that if the counter.php
file has $counter = 5
and the update_counter.php
file is visited by i.e. 1000 users at the exact same time, the file gets read 1000 times at the same time (so the the value 5
gets read in all requests) the counter.php
file will be updated with value 5+1 (=6)
instead of 1005
.
有没有一种方法可以使它在不使用数据库的情况下正常工作?
Is there a way to make it work without using database?
推荐答案
您可以使用flock()
来锁定文件,以便其他进程不写入该文件.
You can use flock()
which will lock the file so that other processes are not writing to the file.
已更新为使用fread()
而不是include()
$fp = fopen("counter.txt", "r+");
while(!flock($fp, LOCK_EX)) { // acquire an exclusive lock
// waiting to lock the file
}
$counter = intval(fread($fp, filesize("counter.txt")));
$counter++;
ftruncate($fp, 0); // truncate file
fwrite($fp, $counter); // set your data
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
fclose($fp);
这篇关于使用PHP访问没有数据库的计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!