Php 更改文件\u put\u contents()的指针

Php 更改文件\u put\u contents()的指针,php,Php,我试图将其写入文本文件,但它将其置于底部,我更希望新条目位于顶部。如何更改文本放置位置的指针?在文件开头添加前缀是非常少见的,因为它需要复制文件的所有数据。如果文件很大,这可能会导致性能不可接受(尤其是当它是一个日志文件时,它经常被写入)。如果你真的想要,我会重新考虑 使用PHP执行此操作的最简单方法如下: $iplog = "$time EST - $userip - $location - $currentpage\n"; file_put_contents("iplog.txt", $ip

我试图将其写入文本文件,但它将其置于底部,我更希望新条目位于顶部。如何更改文本放置位置的指针?

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

使用PHP执行此操作的最简单方法如下:

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

file\u get\u contents
解决方案没有将内容预先添加到文件的标志,并且对于大文件(通常是日志文件)效率不高。解决方案是使用带有临时缓冲区的
fopen
fclose
。如果不同的访问者同时更新您的日志文件,那么您可能会遇到问题,但这是另一个主题(您需要锁定机制或其他)


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

的可能副本可能会有用
$iplog = "$time EST - $userip - $location - $currentpage\n";
file_put_contents("iplog.txt", $iplog . file_get_contents('iplog.txt'));
<?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")
?>