开发者

Simple PHP hit counter incrementing by two?

开发者 https://www.devze.com 2023-02-22 08:24 出处:网络
I made a hit counter for a web app, but am confused as to why it\'s incre开发者_如何学Gomenting by two. I simply set a counter variable from the hitCount.txt file, which contains an integer and write

I made a hit counter for a web app, but am confused as to why it's incre开发者_如何学Gomenting 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;


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 empty src : the browser will consider the empty src 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 not file_get_contents().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号