douxian9010 2018-12-04 22:52
浏览 100
已采纳

写入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);
    }
  • 写回答

1条回答 默认 最新

  • dpjjmo3079 2018-12-04 23:03
    关注

    $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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!