douci1918 2014-05-30 22:53
浏览 75
已采纳

PHP计数器仅覆盖/溢出1个字节的数据,计数器重置(竞争条件)

I know this is a simple question but I downloaded a PHP Counter script from http://www.stevedawson.com/scripts/text-counter.php

which is the first result on google for PHP counter scripts and it worked great as expected.

I tried to see if it messes up by holding refresh in my browser after 255 requests it overflowed back to 0. How would I fix this script? I think the culprit is the filesize() which probably gets only 1 byte of data but it doesn't make sense since 255 is actually 3 bytes of data right? since it saves in plain-text format?

Why would it overflow? it's even PHP it shouldn't overflow just automatically mutate into a bigger datatype.

<?php
    $orderCountFile = "order_num_count.txt";
    if (file_exists($orderCountFile)) {
        $fil = fopen($orderCountFile, r);
        $dat = fread($fil, filesize($orderCountFile)); 
        echo $dat+1;
        fclose($fil);
        $fil = fopen($orderCountFile, w);
        fwrite($fil, $dat+1);
    } else {
        $fil = fopen($orderCountFile, w);
        fwrite($fil, 1);
        echo '1';
        fclose($fil);
    }
?>

Yeah I started to remake the script into another purpose I want to use it to keep track of order numbers for my website.

For a fix I think I have to recast $dat into a bigger integer type but can you even cast in PHP?

Also those r and w are suppose to be strings i think but they are used as constants but it doesn't seem to cause any troubles afaik.

  • 写回答

1条回答 默认 最新

  • dongzi8191 2014-05-30 22:58
    关注

    Use file_get_contents and file_put_contents instead. You still have to consider, that there is a hard limit for that counter as well (see PHP_INT_MAX), but it's significantly higher.

    <?php
    $file = "counter.txt";
    $counter = 0;
    if (file_exists($file)) {
      $counter = file_get_contents($file);
    }
    
    $counter = $counter + 1;
    file_put_contents($file, $counter);
    echo $counter;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法