16
votes

In PHP if you write to a file it will write end of that existing file.

How do we prepend a file to write in the beginning of that file?

I have tried rewind($handle) function but seems overwriting if current content is larger than existing.

Any Ideas?

6
Non-pretty way would be to read file contents, prepend whatever you have, and rewrite the entire file. Not sure if there's another way. If you're making a small modification to a huge file, then this isn't exactly "light", but if you're working on a small 100char file, this'll be fine. - Warty
You may want to do this with UNIX tools, if that's a possibility: stackoverflow.com/questions/54365/… - deceze♦

6 Answers

18
votes

The file_get_contents solution is inefficient for large files. This solution may take longer, depending on the amount of data that needs to be prepended (more is actually better), but it won't eat up memory.

<?php

$cache_new = "Prepend this"; // this gets prepended
$file = "file.dat"; // the file to which $cache_new gets prepended

$handle = fopen($file, "r+");
$len = strlen($cache_new);
$final_len = filesize($file) + $len;
$cache_old = fread($handle, $len);
rewind($handle);
$i = 1;
while (ftell($handle) < $final_len) {
  fwrite($handle, $cache_new);
  $cache_new = $cache_old;
  $cache_old = fread($handle, $len);
  fseek($handle, $i * $len);
  $i++;
}
?>
29
votes
$prepend = 'prepend me please';

$file = '/path/to/file';

$fileContents = file_get_contents($file);

file_put_contents($file, $prepend . $fileContents);
4
votes
$filename  = "log.txt";
$file_to_read = @fopen($filename, "r");
$old_text = @fread($file_to_read, 1024); // max 1024
@fclose(file_to_read);
$file_to_write = fopen($filename, "w");
fwrite($file_to_write, "new text".$old_text);
1
votes

Another (rough) suggestion:

$tempFile = tempnam('/tmp/dir');
$fhandle = fopen($tempFile, 'w');
fwrite($fhandle, 'string to prepend');

$oldFhandle = fopen('/path/to/file', 'r');
while (($buffer = fread($oldFhandle, 10000)) !== false) {
    fwrite($fhandle, $buffer);
}

fclose($fhandle);
fclose($oldFhandle);

rename($tempFile, '/path/to/file');

This has the drawback of using a temporary file, but is otherwise pretty efficient.

-1
votes

When using fopen() you can set the mode to set the pointer (ie. the begginng or end.

$afile = fopen("file.txt", "r+");

'r' Open for reading only; place the file pointer at the beginning of the file.

'r+' Open for reading and writing; place the file pointer at the beginning of the file.

-5
votes
            $file = fopen('filepath.txt', 'r+') or die('Error');
            $txt = "/n".$string;
            fwrite($file, $txt);
            fclose($file);

This will add a blank line in the text file, so next time you write to it you replace the blank line. with a blank line and your string.

This is the only and best trick.