doucheng7234 2013-08-14 15:56
浏览 24
已采纳

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

I have a single webpage and i would like to track how many times it's visited without using a database.

I thought about XML, updating a file every time a user visits the page:

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

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

<?php
    $counter = 0;
?>

update_counter.php:

<?php
    include "counter.php";
    $counter += 1;
    $var = "<?php
\t\$counter = $counter;
?>";
    file_put_contents('counter.php', $var);
?>

With this, everytime update_counter.php is visited, the variable in the counter.php file is incremented.

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?

  • 写回答

5条回答 默认 最新

  • douhao2026 2013-08-14 16:17
    关注

    You can use flock() which will lock the file so that other processes are not writing to the file.

    Edit: updated to use fread() instead of 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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测