【问题标题】:Change pointer for file_put_contents()更改 file_put_contents() 的指针
【发布时间】:2014-08-14 14:26:43
【问题描述】:
$iplog = "$time EST - $userip - $location - $currentpage\n";
file_put_contents("iplog.txt", $iplog, FILE_APPEND);

我正在尝试将其写入文本文件,但它会将其放在底部,如果新条目位于顶部,我会更喜欢。如何更改放置文本的指针?

【问题讨论】:

标签: php


【解决方案1】:

file_get_contents 解决方案没有将内容附加到文件的标志,并且对于日志文件通常是的大文件效率不高。解决方案是将fopenfclose 与临时缓冲区一起使用。如果不同的访问者同时更新您的日志文件,那么您可能会遇到问题,但那是另一个主题(然后您需要锁定机制或其他)。

<?php

function prepend($file, $data, $buffsize = 4096)
{
    $handle = fopen($file, 'r+');
    $total_len = filesize($file) + strlen($data);
    $buffsize = max($buffsize, strlen($data));
    // start by adding the new data to the file
    $save= fread($handle, $buffsize);
    rewind($handle);
    fwrite($handle, $data, $buffsize);
    // now add the rest of the file after the new data
    $data = $save;
    while (ftell($handle) < $total_len)
    {
        $chunk = fread($handle, $buffsize);
        fwrite($handle, $data);
        $data = $chunk;
    }
}

prepend("iplog.txt", "$time EST - $userip - $location - $currentpage\n")
?>

应该这样做(代码已经过测试)。但它需要一个初始的 iplog.txt 文件(或者 filesize 会引发错误。

【讨论】:

    【解决方案2】:

    在文件开头添加前缀非常少见,因为它需要复制文件的所有数据。如果文件很大,这可能会导致性能无法接受(尤其是当它是一个经常写入的日志文件时)。如果你真的想要,我会重新考虑。

    用 PHP 最简单的方法是这样的:

    $iplog = "$time EST - $userip - $location - $currentpage\n";
    file_put_contents("iplog.txt", $iplog . file_get_contents('iplog.txt'));
    

    【讨论】:

      猜你喜欢
      • 2020-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-19
      相关资源
      最近更新 更多