我用PHP调用的数据文件神秘地改变了。 用户是否覆盖了它?

I'm having a blast with PHP functionality, but I know very little about PHP security -- which, of course, is a major bad thing. I'm self-teaching myself this language but the resources are sometimes a little less cut-and-dried than is helpful.

I just made this dumb little site:

http://www.ineedaprompt.com/

You can see that right below the "Again!" button is a counter. It shows how many times the button has been clicked. Every time the button is clicked, my JS makes an Ajax call to a PHP file (counter.php) which updates this file:

http://www.ineedaprompt.com/counter.txt

Every 100ms, I use an Ajax call to update the value of that counter field with the contents of the counter file.

The counter was well over 100 recently, but then suddenly dropped back to 0 and started all over. How easy would it be for someone external to overwrite that counter.txt file? How can I prevent it?

Note: There's nothing in my .htaccess file having to do with PHP because I'm not sure what to put in there.

Pardon my ignorance and TMI, and thank you!

EDIT: You guys are wonderfully fast.

Here's the counter.php code:

<?php

$counter = file_get_contents("counter.txt");

$counter++;

file_put_contents("counter.txt", $counter);

?>

...and the code in my JS that activates on clicking the button:

$("#button").click(function(){
    $.ajax("counter.php");
});

...and the code in my JS that activates every 100ms:

window.setInterval(function(){
    $.get("counter.txt", function(result){
        $("#counter").html(result);
    });
}, 100);

The counter has no limit. It's literally just a text file with a single number in it.

You need to LOCK the file when writing data because The Operating System can't handle multiple read and write at same time, I used below in a site and now my problem solved also. I hope it help you and someone else.

if( $fl = fopen("counter.txt", "r+") && flock( $fl ,  LOCK_EX ) )
{
  //empty the file
  ftruncate($fl, 0); 

  //move file pointer to beginning
  fseek($fl, 0); 
  //write
  fwrite($fl, $content);
  fflush($fl);
  flock($fl, LOCK_UN); 
  fclose($fl); 
}

It's possible that a read and write to the "counter.txt" file is happening at the same time, and when file_get_contents("counter.txt") is called when the file is blank, it returns a blank string.

Then, when you increment, $counter++; on a blank string, it turns into "1". And that "1" gets written to the file.

You could try locking the file, here's an SO answer with some sample code: Read and write to a file while keeping lock