Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 以原子方式将一行追加到文件中,如果没有,则创建该行';不存在_Php - Fatal编程技术网

Php 以原子方式将一行追加到文件中,如果没有,则创建该行';不存在

Php 以原子方式将一行追加到文件中,如果没有,则创建该行';不存在,php,Php,我正在尝试创建一个函数(用于日志记录) 那 如果$file不存在,则创建$file,并且 以原子方式向其追加$data 它必须 支持高并发性 支持长字符串和 尽可能表现出色 到目前为止,最好的尝试是: function append($file, $data) { // Ensure $file exists. Just opening it with 'w' or 'a' might cause // 1 process to clobber another's.

我正在尝试创建一个函数(用于日志记录)

  • 如果$file不存在,则创建$file,并且
  • 以原子方式向其追加$data
  • 它必须

    • 支持高并发性
    • 支持长字符串和
    • 尽可能表现出色
    到目前为止,最好的尝试是:

    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);
    }
    

    它工作正常,但它似乎是一个相当复杂的问题。有没有更干净的(内置的?)方法呢?

    PHP已经有了一个内置的函数来实现这一点。语法是:

    file_put_contents($filename, $data, FILE_APPEND);
    

    请注意,
    file\u put\u contents()

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


    LOCK_EX=>标志,以防止任何其他人同时写入文件(从PHP 5.1开始提供)

    我相信这不会使用模式“x”打开文件(C-land中的O_exc),因此如果文件不存在,您可能会有竞争条件。请看(看起来它只是使用了“c”)30个ups,而不是最佳答案。可怜的世界<代码>:(
    这是错误的答案。这没有正确回答问题:他要求“自动向其添加$data.”和“支持高并发性”。文件内容对于Concurent写入不安全。这是一个比投票最多的解决方案更好的解决方案。文件内容对于Concurent写入不安全。
    file_put_contents($filename, $data, FILE_APPEND);
    
    file_put_contents($file, $data, FILE_APPEND | LOCK_EX);