PHP Increment a counting variable in a text file

前端 未结 5 1929
Happy的楠姐
Happy的楠姐 2020-12-10 20:14

This seems simple but I can\'t figure it out.

file_get_contents(\'count.txt\');
$variable_from_file++;
file_put_contents(\'count.txt\', $variable_from_file);         


        
5条回答
  •  不知归路
    2020-12-10 20:57

    If you want to be sure no increments go uncounted (which is what CodeCaster is referring to, the script may load count.txt, increment it, while another file is doing the same, then save that, and then only one increment would have been done and not the proper two), you should use fopen.

    $fp = fopen('count.txt', 'c+');
    flock($fp, LOCK_EX);
    
    $count = (int)fread($fp, filesize('count.txt'));
    ftruncate($fp, 0);
    fseek($fp, 0);
    fwrite($fp, $count + 1);
    
    flock($fp, LOCK_UN);
    fclose($fp);
    

    This will lock the file, preventing any others from reading or writing to it while the count is incremented (meaning others would have to wait before they can increment the value).

提交回复
热议问题