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;
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 emptysrcpoints 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().