0

我知道这是一个简单的问题,但我从http://www.stevedawson.com/scripts/text-counter.php下载了一个 PHP Counter 脚本

这是 google 上 PHP 计数器脚本的第一个结果,它按预期工作得很好。

我试图通过在 255 个请求溢出回 0 后在我的浏览器中保持刷新来查看它是否搞砸了。我将如何修复这个脚本?我认为罪魁祸首是filesize()它可能只得到 1 个字节的数据,但它没有意义,因为255它实际上3 bytes是数据,对吗?因为它以纯文本格式保存?

为什么会溢出?它甚至是 PHP,它不应该溢出,只是自动变异成更大的数据类型。

<?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);
    }
?>

是的,我开始将脚本重新制作成另一个目的,我想用它来跟踪我网站的订单号。

对于修复,我认为我必须重新$dat转换为更大的整数类型,但你甚至可以在 PHP 中转换吗?

我认为那些rw应该是字符串,但它们被用作常量,但它似乎不会造成任何麻烦。

4

1 回答 1

1

使用file_get_contentsandfile_put_contents代替。您仍然必须考虑,该计数器也有一个硬性限制(请参阅 参考资料PHP_INT_MAX),但它要高得多。

<?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;
于 2014-05-30T22:58:14.393 回答