Atomically appending a line to a file and creating it if it doesn't exist

前端 未结 2 1810
無奈伤痛
無奈伤痛 2021-02-06 22:15

I\'m trying to create a function (for purposes of logging)

append($path, $data)

that

  1. creates $file if it doesn\'t exist and
2条回答
  •  孤街浪徒
    2021-02-06 23:01

    using PHP's internal function http://php.net/manual/en/function.file-put-contents.php

    file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
    

    FILE_APPEND => flag to append the content to the end of the file

    LOCK_EX => flag to prevent anyone else writing to the file at the same time (Available since PHP 5.1)

提交回复
热议问题