简单的 PHP 命中计数器增加 2?
我为一个网络应用程序制作了一个点击计数器,但我很困惑为什么它会增加 2。我只是从 hitCount.txt 文件中设置一个计数器变量,其中包含一个整数,并将预先递增的值写回到文件中。
有问题的代码:
// get visit count
$wag_file = "hitCount.txt";
$fh = fopen($wag_file, 'r+');
$wag_visit_count = intval(file_get_contents($wag_file));
// increment, rewrite, and display visit count
fputs($fh, ++$wag_visit_count);
fclose($fh);
echo $wag_visit_count . $html_br;
I made a hit counter for a web app, but am confused as to why it's incrementing by two. I simply set a counter variable from the hitCount.txt file, which contains an integer and write the pre-incremented value back to the file.
The code in question:
// get visit count
$wag_file = "hitCount.txt";
$fh = fopen($wag_file, 'r+');
$wag_visit_count = intval(file_get_contents($wag_file));
// increment, rewrite, and display visit count
fputs($fh, ++$wag_visit_count);
fclose($fh);
echo $wag_visit_count . $html_br;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想说最合乎逻辑的解释是你的 PHP 脚本被调用了两次。
查看浏览器调用的内容,例如使用 Firebug 的 Net 选项卡。
一个典型的例子是带有空
src
的标签:浏览器会认为空
src
指向当前页面 --并重新加载当前 URL。作为旁注:您应该以读/写模式打开文件并锁定它,以避免并发写入,而不是读取文件然后再将其写回 - 请参阅
flock()
。基本上,由于您已经在 r+ 模式下打开文件,因此应该使用类似
fgets() 的内容
从中读取 - 而不是file_get_contents()
。I'd say the most logical explanation is that your PHP script is called twice.
Take a look at what's called by the browser, using for example the Net tab of Firebug.
A typical example is an
<img>
tag with an emptysrc
: the browser will consider the emptysrc
points to the current page -- and reload the current URL.As a sidenote : instead of reading the file and only then writing it back, you should open your file in read/write mode, and lock it, to avoid concurrent writes -- see
flock()
.Basically, as you are already opening the file in r+ mode, you should use something like
fgets()
to read from it -- and notfile_get_contents()
.