<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith
";
// 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.
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.
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:)
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);
See this answer in an almost identical question.
You probably do not want to use this though, as it looks like you're only working with a small file.