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

I am trying to write this to the text file, but it puts it at the bottom and I would prefer if the new entries were at the top. How would I change the pointer for where it puts the text?

  • possible duplicate of [Need to write at beginning of file with PHP](http://stackoverflow.com/questions/1760525/need-to-write-at-beginning-of-file-with-php) – Clément Malet Jun 24 '14 at 10:54
  • [this question](http://stackoverflow.com/questions/3332262/how-do-i-prepend-file-to-beginning) might be useful – lelloman Jun 24 '14 at 10:54

2 Answers2

1

To prepend at the beginning of a file is very uncommon, as it requires all data of the file copied. If the file is large, this might get unacceptable for performance (especially when it is a log file, which is frequently written to). I would re-think If you really want that.

The simplest way to do this with PHP is something like this:

$iplog = "$time EST - $userip - $location - $currentpage\n";
file_put_contents("iplog.txt", $iplog . file_get_contents('iplog.txt'));
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

The file_get_contents solution doesn't have a flag for prepending content to a file and is not very efficient for big files, which log files usually are. The solution is to use fopen and fclose with a temporary buffer. Then you can have issues if different visitors are updating your log file at the same time, but's that another topic (you then need locking mechanisms or else).

<?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")
?>

That should do it (the code was tested). It requires an initial iplog.txt file though (or filesize throws an error.

achedeuzot
  • 4,164
  • 4
  • 41
  • 56