写入txt文件有效,但是它会不时地转储到txt文件中的所有内容吗?

Hellooo,

I wrote myself a little PHP experiment. This script counts how many times the user clicked a button labeled with a specific class (id="link_1", class="heart")

During each click, the script reads a txt file, finds the right id, then adds +1 to that id's number, like so:

#counte_me.php
$file = 'count_me.txt'; // stores the numbers for each id
$fh = fopen($file, 'r+');
$id = $_REQUEST['id']; // posted from page
$lines = '';
while(!feof($fh)){
    $line = explode('||', fgets($fh));
    $item = trim($line[0]);
    $num = trim($line[1]);
    if(!empty($item)){
        if($item == $id){
            $num++; // increment count by 1
            echo $num;
            }
        $lines .= "$item||$num
";
        }
    }
fclose($fh);
file_put_contents($file, $lines, LOCK_EX);

The result

# count_me.txt
hello_darling||12

This works wonderfully well. The problem happens when, from time to time, I find myself staring at an empty count_me.txt!

Not really know when or how it happens, but it does. I start making increments and happens, sometimes sooner, sometimes way later. It may be on my way to 10 or to 200 or to 320 or anything in between. Its totally random.

Driving me crazy. I'm not experienced enough, but that's why I'm playing with this thing.

Someone knows what I am doing wrong here for the file to get dumped like that?

UPDATE 1 So far, Oluwafemi Sule's suggestion is working, but I have to remove LOCK_EX from the file_put_contents for it to work, otherwise it just doesn't.

    // NEW LINE ADDED
    if (!empty($lines)) {
        file_put_contents($file, $lines);
    }

$lines is initially set to an empty string and only updated on the following condition.

if(!empty($item)) { 
  # and so on and so on
}

And finally at the end,

file_put_contents($file, $lines, LOCK_EX);

The reason that $lines still remains set to the initial empty string happens when item is empty. Remember the newline added from "$item||$num ", there could be more than a single line added there(I won't put it past a text editor to add a new line to end that file .)

I suggest to only write to the file when $lines isn't empty.

if (!empty($lines)) {
    file_put_contents($file, $lines, LOCK_EX);
}