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

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?