PHP-命中计数器文本文件重置

PHP-命中计数器文本文件重置,php,web,refresh,hitcounter,Php,Web,Refresh,Hitcounter,我的非唯一命中计数器有问题 脚本如下: $filename = 'counter.txt'; if (file_exists($filename)) { $current_value = file_get_contents($filename); } else { $current_value = 0; } $current_value++; file_put_contents($filename, $current_value); 当我经常刷新我的网站时(比如每秒刷新10次或

我的非唯一命中计数器有问题

脚本如下:

$filename = 'counter.txt';
if (file_exists($filename)) {
    $current_value = file_get_contents($filename);
} else {
    $current_value = 0;
}
$current_value++;
file_put_contents($filename, $current_value);
当我经常刷新我的网站时(比如每秒刷新10次或更快),文本文件中的值将重置为0


有没有关于修复此问题的猜测?

这是一种维护计数器的非常糟糕的方法,但您的问题可能是,当您在站点上发出多个请求时,对
file_exists()
的一个调用得到了一个false,因为其他进程之一正在删除并重新创建该文件

如果你想让它持续工作,你必须在读写之间锁定文件

当然,如果没有文件锁,当两个进程设法从文件中读取相同的值时,您也会得到错误的计数

锁定该文件还可能会降低系统速度,因为有2个或更多进程排队等待访问该文件


将计数器存储在数据库中可能是一个更好的主意,因为它们是为应对这种快速访问而设计的,并确保每个进程都已正确排队并被释放。

如果您添加一个检查,以检查file\u get\u contents是否返回false,是否有帮助

$value = file_get_contents($filename);
if($value !== false)
{
    $current_value = $value
}
尝试快速启动(
F5
),似乎效果良好。也许是许可问题?