gpt4 book ai didi

php - 使用 PHP 访问没有数据库的计数器

转载 作者:可可西里 更新时间:2023-11-01 12:46:55 24 4
gpt4 key购买 nike

我有一个网页,我想在不使用数据库的情况下跟踪它的访问次数。

我想到了 XML,每次用户访问页面时更新一个文件:

<?xml version='1.0' encoding='utf-8'?>
<counter>8</counter>

然后我认为在单独的文件中声明一个 PHP 计数器然后在每次用户访问该页面时更新它可能是一个更好的主意。

计数器.php

<?php
$counter = 0;
?>

更新计数器.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 文件中的变量都会递增。

无论如何,我注意到如果 counter.php 文件有 $counter = 5 并且 update_counter.php 文件被访问,即1000 个用户在同一时间,文件被同时读取 1000 次(因此值 5 在所有请求中被读取)counter.php 文件将更新为值 5+1 (=6) 而不是 1005

有没有办法不用数据库就可以让它工作?

最佳答案

您可以使用 flock() 来锁定文件,这样其他进程就不会写入文件。

编辑:更新为使用 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 - 使用 PHP 访问没有数据库的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18236599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com