php 原子地将一行附加到文件并在文件不存在时创建它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9096470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:09:23  来源:igfitidea点击:

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

php

提问by Jaka Jan?ar

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. atomically appends $data to it.
  1. 如果 $file 不存在,则创建它,并且
  2. 原子地将 $data 附加到它。

It has to

它必须

  • support high concurrency,
  • support long strings and
  • be as performant as possible.
  • 支持高并发,
  • 支持长字符串和
  • 尽可能提高性能。

So far the best attempt is:

到目前为止,最好的尝试是:

function append($file, $data)
{
    // Ensure $file exists. Just opening it with 'w' or 'a' might cause
    // 1 process to clobber another's.
    $fp = @fopen($file, 'x');
    if ($fp)
        fclose($fp);

    // Append
    $lock = strlen($data) > 4096; // assume PIPE_BUF is 4096 (Linux)

    $fp = fopen($file, 'a');
    if ($lock && !flock($fp, LOCK_EX))
        throw new Exception('Cannot lock file: '.$file);
    fwrite($fp, $data);
    if ($lock)
        flock($fp, LOCK_UN);
    fclose($fp);
}

It works OK, but it seems to be a quite complex. Is there a cleaner (built-in?) way to do it?

它工作正常,但它似乎是一个相当复杂的。有更清洁的(内置的?)方法吗?

回答by FtDRbwLXw6

PHP already has a built-in function to do this, file_put_contents(). The syntax is:

PHP 已经有一个内置函数来执行此操作,file_put_contents()。语法是:

file_put_contents($filename, $data, FILE_APPEND);

Note that file_put_contents()will create the file if it does not already exist (as long as you have file system permissions to do so).

请注意,file_put_contents()如果该文件尚不存在,则将创建该文件(只要您具有文件系统权限即可)。

回答by catalint

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

使用 PHP 的内部函数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

FILE_APPEND => 将内容附加到文件末尾的标志

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

LOCK_EX => 标志以防止其他人同时写入文件(自 PHP 5.1 起可用)