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

Write to txt file works, but it dumps everything in the txt file from time to time?

你好,

我自己写了一个小PHP实验。此脚本计算用户单击标有特定 class (id="link_1", class="heart")

的按钮的次数

每次点击时,脚本都会读取一个 txt 文件,找到正确的 ID,然后将 +1 添加到该 ID 的编号,如下所示:

#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\r\n";
        }
    }
fclose($fh);
file_put_contents($file, $lines, LOCK_EX);

结果

# count_me.txt
hello_darling||12

效果非常好。当我不时发现自己盯着一个空的 count_me.txt 时,就会出现问题!

真的不知道它何时或如何发生,但它确实发生了。我开始增加并发生,有时更快,有时更晚。它可能在我达到 10 或 200 或 320 或介于两者之间的途中。完全随机。

快把我逼疯了。我经验不足,但这就是我玩这个东西的原因。

有人知道我在这里做错了什么让文件像那样被转储吗?

更新 1 到目前为止,Oluwafemi Sule 的建议奏效了,但我必须从 file_put_contents 中删除 LOCK_EX 才能奏效,否则它就不会奏效。

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

$lines 最初设置为空字符串,仅在以下条件下更新。

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

最后,

file_put_contents($file, $lines, LOCK_EX);

$lines 仍然设置为初始空字符串的原因发生在 item 为空时。请记住从 "$item||$num\r\n" 添加的换行符,那里可能会添加不止一行(我不会通过文本编辑器添加新行来结束该文件。)

我建议只在 $lines 不为空时写入文件。

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