PHP Increment a counting variable in a text file

前端 未结 5 1930
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:49

    There is a slightly funnier way:

    file_put_contents("count.txt",@file_get_contents("count.txt")+1);
    

    file_get_contents reads the contents of the counter file.
    @ tells PHP to ignore the error of a missing file. The returned false will then be interpreted as the count of 0.
    +1 will cause the string to be converted to a number.
    file_put_contents then stores the new value in the counter file as a string.

    On a very busy system you might want to obtain a file lock first (if the OS permits) to prevent simultaneous writes.

提交回复
热议问题