2
<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
 file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>

This will append the content at the end of the file. i want to write newest at the beginning of the file.

SheetJS
  • 22,470
  • 12
  • 65
  • 75
Xtream
  • 21
  • 1
  • 2
  • Does this answer your question? [How do I prepend file to beginning?](https://stackoverflow.com/questions/3332262/how-do-i-prepend-file-to-beginning) – Nico Haase Jul 22 '21 at 12:30

3 Answers3

4

As the manual page shows, there is no flag to prepend data.

You will need to read the whole file using file_get_contents() first, prepend the value, and save the whole string.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • How fast do you actually type? :) – Trufa Dec 16 '10 at 11:54
  • no no i don't want to read first and write again ... on the runtime i want to write at the beginning like rewind($handle) is there for fopen() ... i am asking about file_put_cotents(). Thanks. – Xtream Dec 16 '10 at 11:54
  • @Akinator I'm not a ten-finger typer so I'm not horribly fast - but I'm a quick clicker :) @Xtream sorry, I think that is not possible. You'd have to use `fwrite` / `rewind` to do that – Pekka Dec 16 '10 at 11:56
  • @Akinator I'm a `connoisseur of clickers`. But my fingers are cold, I'll practice too :) – Pekka Dec 16 '10 at 12:23
  • And you call you yourself a fast clicker! :P – Trufa Dec 16 '10 at 12:57
2

writing at the beginning of a file might incur some unnecessary overhead on the file-system and the hard-disk.

As a solution, you would have to read the entire file in-memory, write the new content you want added, and then write the old content. This takes time and memory for large files(it depends on the actual workload you have, but as a general rule, its slow).

Would appending normally(at the end) and then reading the file backwards would be a viable solution? This would lead to faster writes, but slower reads. It basically depends on your workload:)

Quamis
  • 10,924
  • 12
  • 50
  • 66
1

You won't have the choice if you want to use file_put_contents, you'll need to read / contatenate / write.

<?
$file = 'people.txt';  
$appendBefore = 'Go to the beach';
$temp = file_get_contents($file);
$content = $appendBefore.$temp;
file_put_contents($file, $content);
Shikiryu
  • 10,180
  • 8
  • 49
  • 75