Q:

Integer number truncated when writing to text file in PHP?

I wrote a download counter:

$hit_count = @file_get_contents('download.txt');
$hit_count++;
@file_put_contents('download.txt', $hit_count);

header('Location: file/xxx.zip');

As simple as that. The problem is the stats number is truncated to 4 digits thus not showing the real count:
http://www.converthub.com/batch-image-converter/download.txt
The batch image converter program gets downloaded a couple hundred times per day and the PHP counter has been in place for months. The first time I found out about this was about 2 months ago when I was very happy that it hit 8000 mark after a few weeks yet a week after that it was 500 again. And it happened again and again.
No idea why. Why?

A:

You're probably suffering a race condition in the filesystem, you're attempting to open and read a file, then open the same file and write to it.  The operating system may not have fully released its original lock on the file when you close it for reading then open it for writing again straight away.  If the site is as busy as you say, then you could even have issues of multiple instances of your script trying to access the file at the same time
Failing that, do all your file operations in one go.  If you use fopen (), flock (), fread (), rewind (), fwrite () and fclose () to handle the hit counter updating you can avoid having to close the file and open it again.  If you use r+ mode, you'll be able to read the value, increment it, and write the result back in one go.  
None of this can completely guarantee that you won't hit issues with concurrent accesses though.
I'd strongly recommend looking into a different approach to implementing your hit counter, such as a database driven counter.  

